Skip to content

Support custom values for integer enums #172

@ryanc414

Description

@ryanc414

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions