How to Use iota in Go: Simple Explanation and Examples
In Go,
iota is a special constant that simplifies creating incrementing numbers in constant declarations. It resets to zero in each const block and increments by one for each line, making it easy to define related constants without manually assigning values.Syntax
The iota keyword is used inside a const block to generate a sequence of incrementing numbers automatically. It starts at 0 for the first constant and increases by 1 for each new line within the same block.
Each time you start a new const block, iota resets to 0.
go
const ( First = iota // 0 Second // 1 Third // 2 )
Example
This example shows how to use iota to create a set of constants representing days of the week. Each constant automatically gets a unique number starting from 0.
go
package main import "fmt" const ( Sunday = iota Monday Tuesday Wednesday Thursday Friday Saturday ) func main() { fmt.Println("Sunday:", Sunday) fmt.Println("Monday:", Monday) fmt.Println("Saturday:", Saturday) }
Output
Sunday: 0
Monday: 1
Saturday: 6
Common Pitfalls
One common mistake is expecting iota to continue counting across multiple const blocks, but it resets to zero each time. Another is forgetting that iota increments with each line, so skipping lines or adding comments can affect values if not careful.
Also, using iota outside a const block causes a compile error.
go
package main import "fmt" const ( A = iota // 0 B // 1 ) const ( C = iota // 0 again, not 2 D // 1 ) func main() { fmt.Println(A, B, C, D) // Output: 0 1 0 1 }
Output
0 1 0 1
Quick Reference
| Concept | Description | Example |
|---|---|---|
| iota | Auto-incrementing number in const block | const (A = iota; B; C) // A=0, B=1, C=2 |
| Reset | iota resets to 0 in each const block | const (X = iota); const (Y = iota) // X=0, Y=0 |
| Usage | Used only inside const blocks | var x = iota // Error |
| Skipping values | Use blank identifier to skip | const (A = iota; _; C = iota) // A=0, C=2 |
Key Takeaways
Use
iota inside const blocks to create incrementing constants easily.iota resets to zero in each new const block.Each line in a
const block increments iota by one automatically.Do not use
iota outside of const blocks; it causes errors.You can skip values or create complex sequences by combining
iota with expressions.