Enums Cheatsheet

Simulated Enums (Custom Types)

Go doesn’t have native enums. Instead, use custom types:

type Color string

const (
    ColorRed   Color = "red"
    ColorBlue  Color = "blue"
    ColorGreen Color = "green"
)

Auto-incrementing Integers (iota)

iota simplifies the creation of related integer constants.

type Size int

const (
    Small  Size = iota // 0
    Medium             // 1
    Large              // 2
)

Key Differences from Other Languages

  • No Sum Types: You can’t define a type that is “Either A or B” with attached data (like Rust).
  • Literal Bypass: Standard literals can still satisfy custom types if the underlying type (e.g., string) is the same.
  • Explicit Conversion: Any value of the underlying type can be cast to your custom “enum” type.

Best Practices

  • Always create a custom type for your enums rather than using raw strings or ints.
  • Use constants to define the valid set of values.
  • If you need a “None” or “Unknown” state, make it the first value in an iota list (so it defaults to 0).