Constants and iota
Values fixed at compile time, and how Go does enums without an enum keyword.
Topic 5 of 98 · 5 min to read · 45 min to build
After this topic you can
- 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.
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.go
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
iota.go
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)The short version
- 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.
Remember: There are no constant slices, maps or structs. Those are
var.Build this before moving on
Write a const block of four order states with iota, then print each one and check one with an if.Then try these in your own editor
- 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.
Official documentation