Iota. 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.
Part 1 Iota is used within a const block with multiple items. It starts at 0 (for the value one) and continues to 1 and 2.
Part 2 If a const entry does not use iota, it is still incremented for that entry. It does not stop incrementing even if unused.
Part 3 Iota can be referenced any number of times within a const entry, but it is only incremented on the following const entry.
Part 4 We print out all the uses of 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 11, 2025 (image).