Enumerations with iota
- Version
- 1.27
- Review
- Draft
Summary#
Go builds enumeration-like sets from a named type and constants. iota is the zero-based index of the constant specification within its const block. Constants declared together in one specification share the same iota. A String method gives each value a readable name.
Syntax#
type Priority int
const (
Low Priority = iota + 1
Normal
Urgent
)
Example#
package main
import "fmt"
type priority int
const (
low priority = iota + 1 // keep zero for "unset"
normal
urgent
)
func (p priority) String() string {
switch p {
case low:
return "low"
case normal:
return "normal"
case urgent:
return "urgent"
default:
return fmt.Sprintf("priority(%d)", int(p))
}
}
type permission uint8
const (
canRead permission = 1 << iota
canWrite
canRun
)
func main() {
var unset priority
fmt.Println(low, urgent, unset, priority(9))
fmt.Printf("%v=%d\n", normal, normal)
granted := canRead | canWrite
fmt.Println(granted, canRun)
fmt.Println(granted&canWrite != 0, granted&canRun != 0)
}
Expected output#
low urgent priority(0) priority(9)
normal=2
3 4
true false
Common mistakes#
The named type does not restrict values, so priority(9) compiles. Validate values that come from outside. Inside String, use %d on the numeric value as shown. Formatting the receiver with %v or %s there can call String recursively.
Version applicability#
These iota rules apply to Go 1.27 and earlier Go versions.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0