Constants and iota
Values fixed at compile time, and how Go does enums without an enum keyword.
By devskills editorial team · Last updated
What a constant is
A constant is a value fixed when the program is compiled and never changed afterwards. It is not a variable you promise not to touch; the compiler enforces it. Try to assign to one and the program will not build.
Use a constant for values that are true for the whole program: a limit, an app name, a tax rate.
Constants
const Pi = 3.14159const Greeting = "hello"const ( MaxUploadMB = 10 AppName = "snapnotes")// A constant with no type written adapts to where it is used.const ten = 10var f float64 = ten // fine: becomes 10.0var i int64 = ten // also fine// A constant with a type written does not adaptconst typed int32 = 100var x int64 = typed // COMPILE ERRORiota — numbering without typing numbers
const ( Pending = iota // 0 Active // 1 Suspended // 2 Deleted // 3)// iota is just a number, so you can do arithmetic with itconst ( _ = iota // skip 0 Small = iota * 10 // 10 Medium // 20 Large // 30)A real enum: its own type, a String method, and a safe zero value
Plain iota constants are untyped integers, so any int can be passed where you meant a state. Giving them a named type (type State int) lets the compiler reject a stray number, and a String() method makes fmt print the name instead of the number.
Start the block with an Unknown (or Invalid) value. Every Go variable starts at its zero value, so a State that was never set is 0. If 0 were Pending, a forgotten assignment would look like a real state and nobody would notice.
1 << iota gives each constant its own bit, which is the Go way to write a set of flags: combine them with |, test with &, and clear one with &^ (AND NOT, an operator many languages do not have).
package mainimport "fmt"// State gets its own type, so a plain int cannot be passed by mistake.type State intconst ( Unknown State = iota // 0, the zero value: "not set yet" Pending // 1 Active // 2 Suspended // 3)// String makes fmt print the name instead of the number.func (s State) String() string { switch s { case Unknown: return "unknown" case Pending: return "pending" case Active: return "active" case Suspended: return "suspended" } return fmt.Sprintf("State(%d)", int(s))}// Perm is a set of bit flags: each constant is its own bit.type Perm uint8const ( Read Perm = 1 << iota // 1 Write // 2 Delete // 4)func main() { var s State // never assigned fmt.Println(s, Active, State(9)) p := Read | Write fmt.Println(p&Write != 0, p&Delete != 0) // true false p &^= Write // clear the Write bit fmt.Println(p == Read) // true}Pitfalls
- Inserting a line renumbers everything after it. If the numbers are stored in a database or sent over the wire, adding
Archivedin the middle silently changes what3means. Append new values at the end, or write the numbers out explicitly once they are persisted. - `iota` resets to 0 in every `const` block and counts lines, not names: a blank
_line still uses up a number. - A typed constant does not adapt.
const Limit int32 = 100cannot be assigned to anint64without a conversion; an untypedconst Limit = 100can. - Untyped constants are exact until used.
const big = 1 << 62is fine;var x int32 = bigdoes not compile, because the value does not fit. The check happens at compile time, not as a runtime overflow. - Only basic values can be constants: numbers, strings, booleans and runes. A slice, map or struct has to be a
var.
Cost and the Go angle
Constants cost nothing at run time: the compiler substitutes the value wherever it is used, and a switch over a small typed enum compiles to a few comparisons. The price of the Go approach is that nothing stops State(9) from existing, which is why the String method above has a fallback, and why code that receives a state from outside should validate it.
For a larger set, go generate with the stringer tool writes the String method for you; it is in the golang.org/x/tools module.
- Write a const block that numbers a set of states with
iota. - Explain why an untyped constant fits a float64 and an int64 but a typed one does not.
- Predict the values
iotaproduces in a block with a skipped first line and arithmetic.
- A constant is fixed at compile time. The compiler enforces it; it is not a promise.
- A constant without a written type adapts to where it is used; a typed one does not.
iotacounts up from 0 through a const block, and you can do maths with it.- Go has no
enumkeyword. A const block withiotanumbers a set of choices.
var.iota, then print each one and check one with an if.- 1Use
iotato generate the even numbers 2, 4, 6. - 2Declare
const ten = 10and assign it to both a float64 and an int64. - 3Give the same constant an explicit type and watch the second assignment stop compiling.