Enum is a data type that represents one value from a fixed set of named values.

Enums are useful when a value should only be one of a small number of known options.

For example:

enum Status {
    Open,
    Closed,
    Pending
}

Go does not have a dedicated enum keyword, but it commonly models enums with constants and iota, which automatically increments integer values.

package main
 
import "fmt"
 
type Status int
 
const (
	Open Status = iota
	Closed
	Pending
)
 
func main() {
	fmt.Println(Open)    // 0
	fmt.Println(Closed)  // 1
	fmt.Println(Pending) // 2
}

In this example, iota starts at 0 for Open and increments for each following constant in the same const block.

Enums are useful for:

  • Modeling state
  • Avoiding magic strings or numbers
  • Making invalid values harder to represent
  • Improving readability

Some languages have explicit enum types, while others model enums using constants, strings, symbols, or union types.

Anki

id: enum-definition deck: Computer Science::Data Types tags: data-types enum

Q: What is an enum? A: An enum is a data type that represents one value from a fixed set of named values.

id: go-iota-enum deck: Computer Science::Data Types tags: data-types enum golang

Q: How does Go commonly model automatically numbered enum-like values? A: Go commonly uses constants with iota, which starts at 0 and increments for each constant in the same const block.