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 = 0CategoryHealth = 1CategoryClothing = 2)
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 mainimport "fmt"func main() {const (Low = iotaMediumHigh)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 mainimport "fmt"const (_ = iotaa = iota + 10b int = iota * 10c 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 mainimport "fmt"const (a = iotab 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)}