Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

go
golang
communitycreator

What is iota in Go?

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)
}
A simple sample

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)
}
iota operations

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)
}
Resetting increments

RELATED TAGS

go
golang
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring