What is iota in Go?

Overview

Sometimes an item has no intrinsic value. For example, we probably don’t want to keep a product’s category as a string in a database table. We don’t care how the categories are titled. However, we do care about the fact that they’re different.

const (
CategoryBooks = 0
CategoryHealth = 1
CategoryClothing = 2
)
Example of const

We may have gone with 17, 43, and 61 instead of 0, 1, and 2. The numbers and their values are completely random. Constants are necessary, yet they can be difficult to understand and manage.

What is iota?

In Go, iota enables declaring progressively expanding numeric constants simple.

Example

Let’s look at the code below:

package main
import "fmt"
func main() {
const (
Low = iota
Medium
High
)
fmt.Printf("Low: %d\nMedium: %d\nHigh: %d\n", Low, Medium, High)
}

Explanation

Low is set to 0 by iota, and the compiler is told that the following constants have rising numeric values.

What are iota operations?

It is feasible to carry out operations when we use iota.

package main
import "fmt"
const (
_ = iota
a = iota + 10
b int = iota * 10
c float64 = iota + 5.1
)
func main() {
fmt.Printf("%v — %T\n", a, a)
fmt.Printf("%v — %T\n", b, b)
fmt.Printf("%v — %T\n", c, c)
}

Resetting increments

The increment of iota is reset whenever the const keyword comes in the code.

package main
import "fmt"
const (
a = iota
b int = iota
)
const (
c = iota
)
func main() {
fmt.Printf("%v — %T\n", a, a)
fmt.Printf("%v — %T\n", b, b)
fmt.Printf("%v — %T\n", c, c)
}

Free Resources