Generate enumerations with iota in Go
Sequential constant codes
iota is a predeclared identifier used in constant declarations. It starts at zero in each const declaration and equals the zero-based index of the current constant specification. A constant specification without a type and expression repeats the previous non-empty specification. This makes sequential status codes easy to declare.
package main
import "fmt"
func main() { const ( Pending = iota Running Finished ) fmt.Println(Pending, Running, Finished)}The output is 0 1 2. The omitted expressions repeat iota, not its previous numeric value. iota increases per specification, not per name; two names in the same specification see the same iota.
Start at one or restart
package main
import "fmt"
func main() { const ( Low = iota + 1 High ) const First = iota fmt.Println(Low, High, First)}The output is 1 2 0. Adding one changes the generated values, not the starting index. A new const declaration resets iota. Go does not have a dedicated enum keyword; these are ordinary constants. Reordering them may change their numeric values, so use explicit codes for persisted or externally specified values.
Try it locally
Declare Small, Medium and Large using iota + 1 and omitted expressions. Print the three codes. Expected: 1 2 3.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constants and Basic Types 06: Generate enumerations with iota in Go
Check the lesson objective before moving on.
What is iota in the first specification of a const group?
If A = iota + 1 and the next specification is B with no expression, what is B?