Master Go Enums with const and iota: A Practical Guide
This article explains how Go implements enumeration using const and the iota counter, provides step‑by‑step code examples, demonstrates alternative type‑based enum patterns, and shows how to add a String method for readable output, helping developers write clean, maintainable constant definitions.
Enums are an important data type composed of key‑value pairs, often used as constant identifiers. While languages like C and Java have native enum support, Go lacks an explicit enum keyword, treating enums essentially as constants.
Basic Setup
First, create a simple Go module using go mod init and an enum.go file.
mkdir enum
cd enum
go mod init enum
touch enum.goUsing const + iota
Define a series of constants for states such as Running, Pending, and Stopped using const and iota:
package main
import "fmt"
const (
Running int = iota
Pending
Stopped
)
func main() {
fmt.Println("State running:", Running)
fmt.Println("State pending:", Pending)
fmt.Println("State Stopped:", Stopped)
}Running this program prints the numeric values 0, 1, and 2.
The iota identifier acts as a constant counter that starts at 0 and increments by one for each line within a const block, simplifying the creation of sequential constants.
const (
a int = iota // a = 0
b int = iota // b = 1
c int = iota // c = 2
)
const d int = iota // d = 0Using iota avoids manually writing many constant definitions, which would be cumbersome in languages without such a feature.
Enum‑like Type Alias
For a more traditional enum appearance, define a new type and associate constants with it:
type State int
const (
Running State = iota
Pending
Stopped
)Adding a String method to the type yields readable output:
func (s State) String() string {
switch s {
case Running:
return "Running"
case Pending:
return "Pending"
case Stopped:
return "Stopped"
default:
return "Unknown"
}
}Running the program now prints the state names instead of numeric values.
Learning a language also means understanding its design philosophy; Go’s approach to enums reflects a preference for simplicity and flexibility.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
