const and iota
const names values fixed at compile time, and inside a const block iota counts up from zero on each line, which makes numbered sets of related constants short and safe.
Build a related group of constants and follow how iota advances.
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.