What is iota in Go, and how is it used to define enumerated constants?
Last updated
iota is a predeclared identifier that auto-increments within a const block: it starts at 0 and increases by 1 for each ConstSpec line, making it the idiomatic way to define enumerated constants.
Resets and increments per const block:
iotais 0 on the first line of aconstgroup and increments by one for each subsequent line, regardless of how many constants are on that line.Expressions carry down: If a line omits its value, it repeats the previous expression with the new
iotavalue, so you write the formula once.Skip values with _: Use the blank identifier
_to skip an unwanted value (often 0).Useful for bit flags:
1 << iotagenerates powers of two for bitmask-style enums.
[lang:go]
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1
Tuesday // 2
)
const (
_ = iota // skip 0
KB = 1 << (10 * iota) // 1 << 10
MB // 1 << 20
)