capypad
0 day streak
go / beginner
Snippet

The iota Constant Generator

iota is a predeclared identifier that represents successive untyped integer constants. It starts at 0 and increments with each ConstSpec in a const block. This is perfect for creating enumerated constants, bit flags, and related values. Each new const block resets iota to 0. Within a block, every line without an explicit value implicitly uses the previous line's iota value plus one.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package main
 
import "fmt"
 
const (
_ = iota
KB ByteSize = 1 << (10 * iota) // 1024
MB // 1048576
GB // 1048576 * 1024
TB // 1099511627776
)
 
const (
FlagA Flags = 1 << iota // 1
FlagB // 2
FlagC // 4
FlagD // 8
)
 
type ByteSize int64
type Flags int
 
func (b ByteSize) String() string {
return fmt.Sprintf("%d B", b)
}
 
const (
_ = iota
January
February
March
April
May
June
July
August
September
October
November
December
)
 
func main() {
fmt.Printf("KB: %d, MB: %d\n", KB, MB)
fmt.Printf("Flags: A=%d, B=%d, C=%d\n", FlagA, FlagB, FlagC)
fmt.Printf("March is month number: %d\n", March)
}
Breakdown
1
const ( _ = iota; KB = 1 << (10 * iota) )
iota starts at 0, so _ ignores it. KB uses iota=1 to compute 1<<10 = 1024
2
MB // uses implicit iota+1 = 2
Line without explicit value continues the pattern: 1 << (10*2) = 1<<20
3
FlagA Flags = 1 << iota
Creates bit flags where each flag is a power of 2: 1, 2, 4, 8
4
January; February; March
Simple enumeration: iota produces 1, 2, 3 (since _ = 0 is skipped)