iota is a predeclared identifier in Go that generates a sequence of untyped integer constants inside a const block. It starts at 0 and increases by one for each constant specification (each line) in the block, which makes it the standard way to write a go iota enum. You combine it with a named type so the constants behave like an enumeration.
Go has no enum keyword, so the idiom is a defined integer type plus a const block that uses iota. This guide shows the basic form, how to skip values, how to build bit flags and how to print names.
iota resets to 0 at the start of every const block and increments after each line. If a line has no expression, Go repeats the previous line's expression, so you write iota only once.
The value depends on the line position within the block, not on how many times you wrote the word iota. Two constants on the same line share the same iota value.
A bare integer constant can be passed anywhere an int fits, which loses type safety. Give the enum its own type so the compiler rejects mix-ups.
Only the first line states the type and iota; the following lines inherit both. Printing Tuesday shows 2, because the type does not know its name yet. The next sections fix that.
Use the blank identifier to skip a value, or add an offset to the expression. Starting at 1 is useful when the zero value should mean "unset".
Because the zero value of every Go variable is 0, an enum that starts at 0 makes a forgotten field look like a valid first choice. Reserving 0 as "unknown" or "unset" prevents silent bugs, for example when decoding data.
Shifting 1 by iota creates one bit per constant, which you can combine with | and test with &.
&^ is Go's bit-clear operator. Use an unsigned type for flags so shifts behave predictably.
Give your type a String() method and fmt will use it automatically for %v and Println.
For large enums, the stringer tool (go run golang.org/x/tools/cmd/stringer) generates this method for you with a //go:generate directive.
Color(9) compiles. Validate input at your boundaries.iota.iota works only inside const declarations, and the constants are untyped unless you give a type.switch over enum values is not checked for completeness by the compiler. Add a default case or use a linter.Not as a language feature. The idiom is a named integer type with constants generated by iota, optionally with a String() method.
It starts at 0 in every const block. Use _ = iota or iota + 1 to start at 1.
No. It is valid only inside a const declaration and resets to 0 in each new block.
iota produces integers, so for string values define a type with a String() method or a lookup table, or write the string constants explicitly.
iota numbers the lines of a const block starting at 0. Pair it with a defined type to build an enum, skip 0 when the zero value should mean unset, use 1 << iota for bit flags, and add a String() method for readable output. Avoid depending on iota values that you persist or send between systems.