The iota Keyword in Go¶
Iota is used to create a sequence of values.
Table of Contents¶
Basics of IOTA Incrementation¶
When the iota keyword is used in a constant declaration, it will
increment by 1 for each following identifier (variable).
By default, iota starts at 0 (zero).
E.g.,
This will assigna := 0, b := 1, and c := 2.
Skipping Incrementations¶
Iota's incrementations can be skipped using a blank identifier (an underscore _).
_) will make iota increment, but it will not be saved into any value.
Starting from a Specific Value¶
You can start iota at a specific value.
Do this by adding a value after the iota keyword:
IOTA Usage Example¶
For example, this program:
package main
import "fmt"
const (
a = iota
b
c
_
d
)
func main() {
var vals []int = []int{a, b, c, d}
for i := 0; i < len(vals); i++ {
fmt.Printf("%d\n", vals[i])
}
fmt.Printf("End of incrementations of constants.\n")
}
Enum in Golang¶
IOTA provides an automated way to create a enum (enumeration) in Golang.
type Size uint8
const (
small Size = iota
medium
large
extraLarge
)
func main() {
fmt.Println(small)
fmt.Println(medium)
fmt.Println(large)
fmt.Println(extraLarge)
}
- We created a new type:
type Size uint8 - Then we declared some
constof typeSize. - The first constant,
small, is set toiotaso it will be set to zero
And so:
fmt.Println(small) >> outputs 0
fmt.Println(medium) >> outputs 1
fmt.Println(large) >> outputs 2
fmt.Println(extraLarge) >> outputs 3
Enums Without IOTA¶
Without IOTA we'd have to explicitly set the values of each of the enum value
Output: