With Go iota
we gain a way to generate groups of constants based on expressions. Within a const
block, iota
always starts at 0 and is incremented by 1 for each item within the block.
We cannot use iota
in an expression that must be evaluated at runtime. The term iota
is like beta: it stands for the letter "I" in Greek, just as beta stands for B.
This Go example uses iota
in several const
blocks within a program. It shows how iota
behaves when we do not use it for an item within a const
.
const
block with multiple items. It starts at 0 (for the value one) and continues to 1 and 2.const
entry does not use iota
, it is still incremented for that entry. It does not stop incrementing even if unused.const
entry, but it is only incremented on the following const
entry.iota
in the program. Iota is like a counter for const
lines within a block.package main
import "fmt"
// Part 1: iota goes from 0 to 2 here.
const (
one = iota
two
three
)
// Part 2: iota starts at 0 for the first const, and is incremented for each following value.
const (
a = 10 // Iota is 0 (but not used)
b = iota // Iota is 1
c = 20 // Iota is 2 (not used)
d = iota // Iota is 3
)
// Part 3: iota is the same for each single const value.
const (
north = iota * iota // Iota is 0
east = iota * iota // Iota is 1
south = iota * iota // Iota is 2
west = iota * iota // Iota is 3
)
func main() {
// Part 4: print out the constants.
fmt.Println(one, two, three)
fmt.Println(a, b, c, d)
fmt.Println(north, east, south, west)
}0 1 2
10 1 20 3
0 1 4 9
Iota cannot be initialized to start at a different value. And it cannot be told to skip over an entry in a const
block. If used on a single const
, it always just means 0.
With const
and iota
, the Go language provides compile-time code generation features. We can specify many constants with just an expression.