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.
- enums1 —
iotaconstant generation - enums2 —
iota+String()for named values
Resources
Section titled “Resources”Exercises
Section titled “Exercises”enums1 test
Section titled “enums1 test”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 )enums2 test
Section titled “enums2 test”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" }