Go Enums: The Right Way to Implement, Iterate and Namespacing Trick
We'll talk about how to use enums in Go, covering everything from number groups to using open-source libraries and what 'iota' means.
Right now, Go (version 1.19) doesn’t have a built-in enum type, something that many other languages do offer.
But fortunately resourceful Go developers have found clever ways to work around this, using what the language already provides.
1. The Idiomatic Way
So you’re wondering how to make enums work in Go when it doesn’t even have a native enum type?
A common practice is to define a set of unique integers as constants and use those to represent the enum values
type Color int const ( Red Color = iota // 0 Blue // 1 Green // 2 )
This method of using a group of unique integers to act as enum values is pretty standard in Go and the usual guidance is to start the enum values from 1, saving 0 for ‘undefined’ or a default state. It’s a straightforward way to have enums in Go.
In the example above, we didn’t set a default value, let’s say I don’t want the default color to be red when initialized.
In that case, a small tweak can be made:
const ( Red Color = iota + 1 // 1 Blue // 2 Green // 3 )
And if you really want, you can add an ‘Undefined’ member as the first initialized value, or any other color you consider default, like ‘Black’;
const ( Undefined Color = iota // 0 Red // 1 Blue // 2 Green // 3 )
“This seems too basic. Got anything more interesting?”
Absolutely, you can certainly stretch the functionality of the iota identifier. For example, if you’re interested in an enum sequence that starts at 2 and goes up by 2s, like 2, 4, 6, that’s doable:
const ( Red Color = (iota + 1) * 2 // 2 Blue // 4 Green // 6 )
We add 1 to iota here to make sure ‘
Red’ doesn’t start at 0, which would give us a sequence like 0, 2, 4 instead.
“Can I exclude a specific number from the sequence? Say, skip the number 2?”
Yes, you can.