Golang Iota for Enumerations
Go has an interesting way to alias enumeration values using the iota
keyword. Iota helps increment integer values inside your block or declaration. Consider the following code:
type Gender intconst(
UNKNOWN Gender = 0
FEMALE = 1
MALE = 2
)
Using the iota
keyword you can instead alias your values:
type Gender intconst(
UNKNOWN Gender = iota
FEMALE = iota
MALE = iota
)
The first use of iota
within the factor block returns 0. Whenever iota
is used again on a new line it is incremented by 1. So FEMALE = 1, MALE = 2. A new const block or declaration will initialize iota
back to 0.
You can further shorten this by just invoking iota once:
type Gender intconst(
UNKNOWN Gender = iota
FEMALE
MALE
)
This has the same effect as assigning the individually on each line. You can also skip numbers like so:
type Color intconst(
WHITE Color = iota
RED
ORANGE
YELLOW
_
_
GREEN
BLUE
PURPLE
)
In the above example WHITE is 0, YELLOW is 3, and GREEN is 6 (because the two _ lines skip 4 and 5).
Why do this? Well in Go you cannot easily interchange integers and custom types in functions; however, you can with integer constants. Go treats integer constants loosely until they’re used in a strict context. You can check out Katrin Owen’s article (https://splice.com/blog/iota-elegant-constants-golang/ ) which goes into details about this technique for writing elegant constants.