Go Enums
An enum is a set of named whole-number values. Each name in the set stands for one number.
Counting with iota
iota starts at 0 in this const block. The three names print in order as 0, 1, and 2.
package main
import "fmt"
func main() {
const (
Low = iota
Mid
High
)
fmt.Println(Low)
fmt.Println(Mid)
fmt.Println(High)
}Doubling with a shift
The expression 1 << iota doubles at each step. The three names print as 1, 2, and 4.
package main
import "fmt"
func main() {
const (
Read = 1 << iota
Write
Exec
)
fmt.Println(Read)
fmt.Println(Write)
fmt.Println(Exec)
}A value with a label
A hand-written label prints beside the chosen value. The word names the size, and the number comes from the enum.
package main
import "fmt"
func main() {
const (
Small = iota
Medium
Large
)
size := Medium
fmt.Println("Medium:", size)
}Example
package main
import "fmt"
func main() {
const (
Tiny = iota
Regular
Grand
)
fmt.Println("Tiny:", Tiny)
fmt.Println("Regular:", Regular)
fmt.Println("Grand:", Grand)
}Key points
- Use an enum to give clear names to a small set of numbers.
- iota is a counter that starts at 0 inside a const block.
- Each next name in the block raises iota by 1.
- An enum value is a plain whole number once the program runs.
In this example, the const block names three sizes with iota. Tiny holds 0, Regular holds 1, and Grand holds 2. Each print line pairs a size value with a hand-written label.
Note
Go has no enum keyword. A const block with iota does the job.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
A const block starts with First = iota and names two more values below it. What numbers do the three names hold?