go-enum icon indicating copy to clipboard operation
go-enum copied to clipboard

Support custom values for integer enums

Open ryanc414 opened this issue 2 years ago • 2 comments

Context: a performant way to implement a set of integer enum values is to combine all the values in a single int. For example, let's say we want to implement a set of colours:

type Colour int32

const (
	ColourRed Colour = 1 << iota
	ColourGreen
	ColourBlue
)

func main() {
	colourSet := ColourRed | ColourGreen
	printColours(colourSet)
}

func printColours(colourSet Colour) {
	if colourSet&ColourRed != 0 {
		fmt.Println("Red")
	}

	if colourSet&ColourGreen != 0 {
		fmt.Println("Green")
	}

	if colourSet&ColourBlue != 0 {
		fmt.Println("Blue")
	}
}

It would be great to use this technique with enums generated by go-enum. However, by default the enum values are always strictly incrementing in value, rather than incrementing the bit position. I'm not sure if there is any way to override the default way that values are generated but still use the other features of the package?

ryanc414 avatar Jan 31 '23 15:01 ryanc414

I think that might be worth investigating as an option, but while I come up with a nice way of handling that scenario (for a small use case) is to simply put the integer value after each name (this already works)

ENUM(
  Green = 1
  Blue = 2
  Red = 4
  Yellow = 8
)

abice avatar Feb 01 '23 01:02 abice

Ah great I didn't know you could do that, thanks.

ryanc414 avatar Feb 01 '23 10:02 ryanc414