Go by Example

Enums

Go has no built-in enum type - idiomatic enums use typed integer constants with iota to generate sequential values.

An enumeration is a named set of related options. Go has no special enum type, so a common pattern uses a named integer type with constants. iota gives each constant in the group a number starting at zero.

These named constants represent directions. The switch also returns a fallback for values outside the listed options.

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 that a switch covers every option. A value read from outside the program can also be an unexpected number, so include a default case and check external values.

Enjoyed this? Get more software craft delivered to your inbox.