Enums in Golang (Quick Tip)

For those of you like me who Go is not the first language you learned, you might be familiar with “Enums” or “Enumerated Types”.

While Go does not have an enum per-say you can achieve the same effect with very little effort.

The manual has a very good example if perhaps a little complicated, so please allow me to simplify.

To achieve an enum you will need 2 parts.
The first is the definition of the type itself and what the underlying type is.
And the second is the list of values.

For example a “enum” list of colors that maps back to an integer for easy storage in a db might look like this:

Hopefully the only thing about the above example that needs explaining is “iota”.   While the language spec explains it in a far more geeky way, I like to think of it as the “array index” or for my Java friends the Enum.ordinal().  Basically the position in the list of values, starting with 0.

Enjoy!



Loading Facebook Comments ...