Have you ever wondered how iota
works in Go?
Basically, iota is the index of the constant inside a multi-constant (const (...)
) declaration.
So the value of iota
for the first constant is 0
, the second constant is 1
, and so on.
This only works for constants, not var
s.
This is probably best explained with an example.
package main
import "fmt"
type day int
const (
// Start counting days from 1, so ignore 0.
_ day = iota
// evaluates to the same as the RHS of the previous expression,
// which is iota,
// which is the index of this const expression in this const block,
// which is 1
monday
// this time the index is 2
tuesday
// etc.
wednesday
thursday
friday
saturday
sunday
)
func (d day) String() string {
days := []string{
"",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
}
return days[d]
}
func main() {
// Let's do some wat maths. Waths if you will.
// Test your understanding by guessing the answers:
printDay(monday + tuesday)
printDay(sunday - wednesday)
printDay(tuesday * wednesday)
printDay(saturday / tuesday)
printDay(sunday % wednesday)
printDay(friday & thursday)
printDay(sunday ^ thursday)
}
func printDay(d day) {
fmt.Println(d)
}
You can run the above code in a Go Playground if you want to check your answers.