Dev Skills

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 iota produces 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.14159
const Greeting = "hello"
const (
MaxUploadMB = 10
AppName = "snapnotes"
)
// A constant with no type written adapts to where it is used.
const ten = 10
var f float64 = ten // fine: becomes 10.0
var i int64 = ten // also fine
// A constant with a type written does not adapt
const typed int32 = 100
var x int64 = typed // COMPILE ERROR
A constant without a written type is called **untyped**. Go treats it as "just the number 10" until you put it somewhere, then it takes that type. That is why the same `ten` fits in both a `float64` and an `int64`.

iota — 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 it
const (
_ = iota // skip 0
Small = iota * 10 // 10
Medium // 20
Large // 30
)
`iota` starts at 0 in each `const` block and goes up by one per line. A line with no `=` repeats the previous expression with the next `iota`. Go has no `enum` keyword; this is how you number a set of choices. In **Methods and embedding** you will give them a type and make them print as words.
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.
  • iota counts up from 0 through a const block, and you can do maths with it.
  • Go has no enum keyword. A const block with iota numbers 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
  1. 1Use iota to generate the even numbers 2, 4, 6.
  2. 2Declare const ten = 10 and assign it to both a float64 and an int64.
  3. 3Give the same constant an explicit type and watch the second assignment stop compiling.
Check yourselfTake the Getting started test