Module lessons (3/5)
Constants and iota
Constants are immutable values known at compile time. In Go they are
declared with const and can be typed or untyped. Untyped ones have a
superpower: they adapt to the type required by the context, sparing you
from having to write explicit conversions.
Basic syntax
const PI = 3.14
const MaxRetry int = 5
const Name = "eLearner"MaxRetry is typed (int): you can assign it only to an int.
PI and Name are untyped: they behave like "literals" and adapt to
the context.
const PI = 3.14
var f float32 = PI // ok: PI è non tipata, diventa float32
var d float64 = PI // okconst blocks
You can group several constants in a block:
const (
StateInitial = "INIT"
StateReady = "READY"
StateError = "ERROR"
)iota: the enumeration counter
Inside a const block, the special identifier iota starts at 0
and increments by 1 on each line. It is the idiom for making enumerations:
const (
Monday = iota // 0
Tuesday // 1
Wednesday // 2
Thursday // 3
Friday // 4
)Subsequent lines inherit the expression if they don't provide one.
That's why writing Tuesday is enough without repeating = iota.
Patterns with expressions
iota can appear inside arbitrary expressions:
const (
KB = 1 << (10 * (iota + 1)) // 1 << 10 = 1024
MB // 1 << 20
GB // 1 << 30
TB // 1 << 40
)Skipping a value
If you don't want to assign a value to a line (because you want iota to
increment anyway), use the blank identifier _:
const (
_ = iota // scarta 0
KB // 1
MB // 2
)Your turn
Declare a constant PI with value 3.14 at package level, then print it inside main.
Show hint
`const PI = 3.14` goes at package level, outside main.
Solution available after 3 attempts
Define a const block with the days of the week (Monday, Tuesday, Wednesday) numbered from 1 using iota.
Show hint
Use `iota + 1` on the first line of the block; subsequent lines inherit the expression.
Solution available after 3 attempts
What does this program print?
const (
A = iota * 2
B
C
)
fmt.Println(A, B, C)Recap
constfor immutable values known at compile time.- Untyped constants adapt to the context: no conversion needed.
const ( ... )blocks group related values.iotastarts at 0 in every block and increments line by line.- Patterns: enum (
= iota), bitmask (= 1 << iota), units (= 1 << (10*iota)).