Enums
Go has no built-in enum type - idiomatic enums use typed integer constants with iota to generate sequential values.
Go has no dedicated enum type. A common pattern is a named integer type with constants; iota is the index of each constant specification in its declaration, starting at zero.
This typed constant group represents directions. The switch also returns a fallback for values outside the declared constants.
package main
import "fmt"
type Direction uint8
const (
Unknown Direction = iota
North
East
South
West
)
func label(d Direction) string {
switch d {
case North:
return "north"
case East:
return "east"
case South:
return "south"
case West:
return "west"
case Unknown:
return "unknown"
default:
return "invalid"
}
}
func main() {
fmt.Println(label(East))
}In production
The compiler does not check whether a switch handles every enum constant. Values converted from integers or decoded from input can also be outside the declared set, so keep a default case and validate external values.
Enjoyed this? Get more software craft delivered to your inbox.