In Go, iota is a predeclared identifier that is used to simplify the creation of enumerated constants. It is reset to 0 whenever the const keyword is used and increments by 1 for each subsequent constant declaration within the same const block.
Here’s a simple example:
package main
import "fmt"
const (
A = iota // 0
B = iota // 1
C = iota // 2
)
func main() {
fmt.Println(A, B, C) // Output: 0 1 2
}
You can also use iota in more complex scenarios, such as defining constants with different values:
const (
_ = iota // ignore first value by assigning to blank identifier
KB = 1 << (10 * iota) // 1 << (10 * 1) = 1024
MB = 1 << (10 * iota) // 1 << (10 * 2) = 1048576
GB = 1 << (10 * iota) // 1 << (10 * 3) = 1073741824
)
func main() {
fmt.Println(KB, MB, GB) // Output: 1024 1048576 1073741824
}
In this example, iota is used to create constants for kilobytes, megabytes, and gigabytes, demonstrating its utility in defining related constants efficiently.
