Constants and iota
In this page:
Declaring Constants
The const keyword declares a value that is fixed at compile time and can never be reassigned. Constants are useful for values like mathematical constants, configuration limits, or labels that should never accidentally change during the program's execution.
Example: Declaring Constants
package main
import "fmt"
const MaxRetries = 3
func main() {
fmt.Println("Max retries allowed:", MaxRetries)
}
Login to try C/C++/Java/PHP code in the editor
Grouped Constants
Like var, multiple related constants can be declared together in a parenthesized const block, which keeps a group of fixed values organized and easy to scan.
Example: Grouped Constants
package main
import "fmt"
const (
StatusOK = 200
StatusNotFound = 404
StatusError = 500
)
func main() {
fmt.Println(StatusOK, StatusNotFound, StatusError)
}
Login to try C/C++/Java/PHP code in the editor
Introducing iota
Inside a const block, the identifier iota starts at 0 on the first line and increases by 1 for each subsequent line, even if you don't write it explicitly on every line. This gives you a compact way to generate a sequence of related constant values without typing each number by hand.
Note: iota resets to 0 at the start of each new const( ) block.
Example: Introducing iota
package main
import "fmt"
const (
Sunday = iota
Monday
Tuesday
Wednesday
)
func main() {
fmt.Println(Sunday, Monday, Tuesday, Wednesday)
}
Login to try C/C++/Java/PHP code in the editor
Using iota for Enumerated Values
iota is often combined with simple expressions to create meaningful enumerations, such as byte-size units or status categories, where the exact numeric value matters less than each constant being distinct and ordered.
Example: Using iota for Enumerated Values
package main
import "fmt"
const (
_ = iota // skip 0
KB = 1 << (10 * iota)
MB
GB
)
func main() {
fmt.Println("KB:", KB, "MB:", MB, "GB:", GB)
}
Login to try C/C++/Java/PHP code in the editor
- Trying to reassign a const, which is a compile-time error since constants are immutable by definition.
- Using iota expecting it to reset per const block when it actually increments once per line/spec, not per group of names.
- Assuming const works for values only known at runtime (like the result of a function call) -- const requires a compile-time constant expression.
- const declares a value that cannot change after compilation.
- Constants must be assigned a compile-time constant expression, not a runtime computation.
- iota is a special identifier that auto-increments within a const block, starting at 0.
- iota is commonly used to build readable enumerated constants.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: