Iota
July 14, 2023
You may recall from yesterday that you can omit the constant expression for all but the first ConstantSpec in a parenthesized constant declaration, but that it wasn’t very useful by itself.
Enter iota
…
Iota
Within a constant declaration, the predeclared identifier
iota
represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero. It can be used to construct a set of related constants:const ( c0 = iota // c0 == 0 c1 = iota // c1 == 1 c2 = iota // c2 == 2 ) const ( a = 1 << iota // a == 1 (iota == 0) b = 1 << iota // b == 2 (iota == 1) c = 3 // c == 3 (iota == 2, unused) d = 1 << iota // d == 8 (iota == 3) ) const ( u = iota * 42 // u == 0 (untyped integer constant) v float64 = iota * 42 // v == 42.0 (float64 constant) w = iota * 42 // w == 84 (untyped integer constant) ) const x = iota // x == 0 const y = iota // y == 0
With the automatic iota
constant, we can expand yesterday’s example to do something interesting:
const (
one = iota+1
two
three
)
fmt.Println(one, two, three)
Now it prints: 1 2 3
And what’s more, as you can see in the quoted examples above, you can perform various operations on the iota
result, to manipulate it to a form you care about:
const (
a = string(byte(iota + 65))
b
c
)
fmt.Println(a, b, c)
Prints: A B C
But you don’t have to combine iota
with the omitted expression. You can explicitly use iota
on all, or only some, of the ConstantSpecs:
a = string(byte(iota + 65))
b
c = iota
d
e = iota * 10
f
)
fmt.Println(a, b, c, d, e, f)
Prints: A B 2 3 40 50
Quotes from The Go Programming Language Specification Version of December 15, 2022