Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom values for integer enums #172

Open
ryanc414 opened this issue Jan 31, 2023 · 2 comments
Open

Support custom values for integer enums #172

ryanc414 opened this issue Jan 31, 2023 · 2 comments

Comments

@ryanc414
Copy link

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 ryanc414 changed the title Support custom values for integer enum values Support custom values for integer enums Jan 31, 2023
@abice
Copy link
Owner

abice commented Feb 1, 2023

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
)

@ryanc414
Copy link
Author

ryanc414 commented Feb 1, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants