Module lessons (3/5)
Constants and iota
Compile-time and enum constants with iota
Use untyped constants and iota to eliminate magic numbers and duplications.
Constants represent immutable values computed entirely at compile time. In Go they can be typed or untyped: the latter act as high-precision literals capable of adapting to the type of the context of use.
Typed vs. untyped constants
package main
import "fmt"
const Pi = 3.1415926535 // non tipata: massima precisione compile-time
const MaxRetries int = 5 // tipata: vincolata al tipo int
func main() {
var single float32 = Pi // valido: Pi si adatta a float32
var double float64 = Pi // valido: Pi si adatta anche a float64
var limit int = MaxRetries
fmt.Println(single, double, limit)
}const blocks and domain values
To group configurations or symbolic states linked to the same concept, a const block is used:
package main
import "fmt"
const (
StateInitial = "INIT"
StateReady = "READY"
StateError = "ERROR"
)
func main() {
fmt.Println(StateInitial, StateReady, StateError)
}iota: The enumeration generator
Inside a const block, the special identifier iota starts at 0 on the first line and increments by 1 with each subsequent declaration of the block. Rows without expression automatically inherit the previous formula:
package main
import "fmt"
const (
Monday = iota // 0
Tuesday // 1
Wednesday // 2
Thursday // 3
Friday // 4
)
func main() {
fmt.Println(Monday, Wednesday, Friday)
}Bitmask and explicit jumps with _
Combining iota with the bitwise shift << gives you powers of two ready for combinable permissions, and you can discard the 0 with _:
package main
import "fmt"
const (
_ = iota // 0 scartato come sentinel "non impostato"
KB int64 = 1 << (10 * iota) // 1 << 10 = 1024
MB // 1 << 20 = 1048576
GB // 1 << 30
)
const (
FlagRead = 1 << iota // 1 (001)
FlagWrite // 2 (010)
FlagExec // 4 (100)
)
func main() {
fmt.Println(KB, MB, GB)
fmt.Println(FlagRead|FlagWrite, FlagExec)
}Guided practice
Declare an untyped constant Pi with value 3.14 at the package level, then print it inside main.
Show hint
Write const Pi = 3.14 outside main without specifying an explicit type.
Solution available after 3 attempts
Define a const block with Monday, Tuesday and Wednesday numbered starting from 1 thanks to iota + 1.
Show hint
Use Monday = iota + 1 in the first line of the const ( ... ) block; the following lines inherit the expression.
Solution available after 3 attempts
Create a const block with three bitwise flags (FlagRead, FlagWrite, FlagExec) using 1 << iota so that they are 1, 2, and 4, then print them by combining read and write with |.
Show hint
Set FlagRead = 1 << iota as the first line of the block and leave only the names in the next two lines.
Solution available after 3 attempts
Check for understanding
What does this program print?
const (
A = iota * 2
B
C
)
fmt.Println(A, B, C)Why doesn't the const start = time.Now() statement compile in Go?
const start = time.Now()