Skip to content

Enums

Intermediate · Types & Methods

Go has no enum keyword. The idiom is a named integer type plus a const block using iota, which produces 0, 1, 2, … for successive constants. Add a String() method for readable names.

  • enums1iota constant generation
  • enums2iota + String() for named values

Go has no enum keyword; the idiom is a named integer type plus a const block

Show hint
After the first iota line, list the rest and iota increments automatically:
const ( Sunday Weekday = iota; Monday; Tuesday; Wednesday; Thursday; Friday; Saturday )

Source

Pair iota constants with a String() method to get readable names (and free

Show hint
Switch on the receiver:
switch c { case Red: return "Red"; case Green: return "Green"; case Blue: return "Blue"; default: return "Unknown" }

Source