Constants and iota enums
Context
Section titled “Context”iota is a predeclared identifier in Go that represents successive untyped integer constants. It is used to create enumerated constants (enums) easily.
iotaresets to0at the start of eachconstblock.- Within the block, each
constline incrementsiotaby 1.
Example
Section titled “Example”Define days of the week and bit flags using iota.
Code example
Section titled “Code example”package main
import "fmt"
const ( Sunday = iota // 0 Monday // 1 Tuesday // 2 Wednesday // 3 Thursday // 4 Friday // 5 Saturday // 6)
const ( Read = 1 << iota // 1 << 0 = 1 Write // 1 << 1 = 2 Exec // 1 << 2 = 4)
func main() { fmt.Println(Sunday, Monday, Tuesday) fmt.Println(Read, Write, Exec)}Output
Section titled “Output”0 1 21 2 4