Enums in Golang
GO does not natively support an enum keyword; however, an enum-like syntax can be implemented using the help of iota.
What is iota?
iota is an identifier that auto increments constants.
In the following code, the constant number is manually incremented:
1const (
2 ZERO = 0
3 ONE = 1
4 TWO = 2
5)however, it can be simplified to:
1const (
2 ZERO = iota // 0
3 ONE // 1
4 TWO // 2
5)If desired, the iota keyword can be used on each line:
1const (
2 ZERO = iota // 0
3 ONE = iota // 1
4 TWO = iota // 2
5)If a const keyword is used again, the iota will reset to 0.
1const (
2 ZERO = iota // 0
3 ONE // 1
4 TWO // 2
5)
6
7const (
8 ZEROAGAIN = iota // 0
9 ONEAGAIN // 1
10 TWOAGAIN // 2
11)Implementing an enum in GO
Using a combination of iota, int and const, the concept of an enum can be applied.
1package main
2
3import "fmt"
4
5type PizzaSize int
6
7const (
8 SMALL PizzaSize = iota + 1 // 1
9 MEDIUM // 2
10 LARGE // 3
11)
12
13func (s PizzaSize) String() string {
14 return [...]string{"Small", "Medium", "Large"}[s-1]
15}
16
17func (s PizzaSize) Index() int {
18 return int(s)
19}
20
21func main() {
22 size := SMALL
23 fmt.Println(size) // Print : Small
24 fmt.Println(size.String()) // Print : Small
25 fmt.Println(size.Index()) // Print : 1
26}