capypad
0 day streak
go / beginner
Snippet

Constants with iota for Enumerated Values

The `iota` keyword generates consecutive untyped integer constants. In the first block, it creates color codes (1, 2, 3). In the second block, `1 << iota` creates bit flags (1, 2, 4). The underscore `_` skips the zero value.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main
 
import "fmt"
 
const (
_ = iota
Red int = iota
Green
Blue
)
 
const (
Flag1 uint = 1 << iota
Flag2
Flag3
)
 
func main() {
fmt.Printf("Colors: Red=%d, Green=%d, Blue=%d\n", Red, Green, Blue)
fmt.Printf("Flags: Flag1=%d, Flag2=%d, Flag3=%d\n", Flag1, Flag2, Flag3)
}
Breakdown
1
const ( _ = iota
Underscore discards iota=0, starting enumeration at 1
2
Red int = iota
First named constant, iota=1, explicit type int
3
Green
Same type as Red, iota increments to 2 automatically
4
Flag1 uint = 1 << iota
Bit shift creates powers of 2: 1<<1 = 1
5
Flag2
iota=2, so 1<<2 = 2
6
Flag3
iota=3, so 1<<3 = 4