const and iota
tally will let the user choose how to sort the results: by count, by word, or by length. You want names for those choices, the names must never change while the program runs, and you do not want to number them by hand. That is exactly what const and iota are for.
The rule
const is fixed at compile time; iota counts lines in a const block, from zero.
A constant is a value the compiler knows and nobody can reassign:
const defaultFile = "notes.txt"
const maxWords = 10_000Constants can be numbers, strings, booleans or runes — not slices, maps or structs. Numeric constants written without a type are untyped: they are exact, and take on a type only where they are used. That is why const big = 1 << 40 fits happily into a float64 or an int64 wherever you use it.
iota only has meaning inside a const declaration. It is 0 on the block's first line and goes up by 1 on each following line. A line with no = repeats the expression above it, with the new iota:
type SortOrder int
const (
ByCount SortOrder = iota // 0
ByWord // 1
ByLength // 2
)Tricks built on the same rule:
const (
_ = iota // skip 0
KB = 1 << (10 * iota) // iota 1: 1 << 10 = 1024
MB // iota 2: 1 << 20
)Each new const block starts iota at 0 again.
The shortcut
To read an iota block, write the line numbers 0, 1, 2… down the side, then plug each into the last expression you saw.
Number the lines
_is line 0,KBline 1,MBline 2.
The trap: iota values are positions, not promises. Insert a line in the middle and every later value shifts, so do not store these numbers in files or databases.
Drills
Answer fast — trust the rule.
In const ( A = iota; B; C ), what is C?
Which of these can be a Go constant?
In const ( _ = iota; Low; High ), what is High?
In const ( X = iota * 10; Y; Z ), what is Z?
What happens when you write defaultFile = "other.txt" for a const defaultFile?
Remember
- const is fixed at compile time; iota counts lines in a const block, from zero.
- Shortcut: number the lines, then plug each number into the last expression.
- Trap: inserting a line shifts every value after it; do not persist iota numbers.
