go / beginner
Snippet
Konstanten mit iota für aufzählende Werte
Das Schlüsselwort `iota` erzeugt aufeinanderfolgende unveränderliche Ganzzahlkonstanten. Im ersten Block erstellt es Farbcodes (1, 2, 3). Im zweiten Block erzeugt `1 << iota` Bitflags (1, 2, 4). Der Unterstrich `_` überspringt den Nullwert.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package mainimport "fmt"const (_ = iotaRed int = iotaGreenBlue)const (Flag1 uint = 1 << iotaFlag2Flag3)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)}
Erklärung
1
const ( _ = iota
Unterstrich verwirft iota=0, startet bei 1
2
Red int = iota
Erste benannte Konstante, iota=1, explizit int
3
Green
Gleicher Typ wie Red, iota erhöht sich automatisch auf 2
4
Flag1 uint = 1 << iota
Bitverschiebung erzeugt Zweierpotenzen: 1<<1 = 1
5
Flag2
iota=2, also 1<<2 = 2
6
Flag3
iota=3, also 1<<3 = 4