Constants & iota
Compile-time values and Go's auto-incrementing identifier.
Gopher narrator
Have the gopher read this explanation out loud.
Constants use const and are fixed at compile time. Inside a const (...) block, iota starts at 0 and increases by one per line — handy for enum-like values. It resets to 0 at the start of each new const block.
const Pi = 3.14159
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
)Exercise 1·code
Declare a Weekday type with an iota-based const block for Sunday..Saturday (Sunday = 0). Implement isWeekend(d Weekday) bool returning true for Saturday and Sunday only. A hidden test suite covers every day.
Plate · main.go
Loading...
Test suite · go test
- TestDayValuespending
- TestIsWeekendWeekdayspending
- TestIsWeekendWeekendpending
Hint
Inside the const block set the first line to Sunday Weekday = iota; the rest inherit the type and increment automatically.
Exercise 2·mcq
Inside a const block, iota resets to 0…