Go🔧Core Languagebeginner
Constants and iota
Go · Core Language · Run with go run
Explanation
Constants are immutable values fixed at compile time, declared with `const`. The `iota` identifier is a constant generator that starts at 0 within a `const` block and increments by one for each line — it is the idiomatic way to create enumerated values. Untyped constants in Go have arbitrary precision and adapt to whatever type the context requires.
Real-World Scenario
Defining a set of log levels (`Debug`, `Info`, `Warn`, `Error`) — `iota` assigns 0, 1, 2, 3 automatically, so inserting a new level later renumbers everything without manual edits.
Quick Snippet
snippet.go
const Pi = 3.14159 // untyped constant
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
)
// iota with expressions — byte-size units
const (
_ = iota // skip 0
KB = 1 << (10 * iota) // 1 << 10
MB // 1 << 20
GB // 1 << 30
)Full Example
constants.go
// Compile: go run constants.go
// Output:
// Pi: 3.14159
// Wednesday is day 3
// 1 MB = 1048576 bytes
// 1 GB = 1073741824 bytes
package main
import "fmt"
const Pi = 3.14159
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
)
// iota with a shift expression — byte-size units
const (
_ = iota // skip 0
KB = 1 << (10 * iota) // 1 << 10
MB // 1 << 20
GB // 1 << 30
)
func main() {
fmt.Println("Pi:", Pi)
fmt.Println("Wednesday is day", int(Wednesday))
fmt.Println("1 MB =", MB, "bytes")
fmt.Println("1 GB =", GB, "bytes")
}
Run command
go run constants.go