iota
iota is a predeclared identifier that counts from 0 in a const block, incrementing on each new line. It is how Go writes related constants and bit flags without a separate enum type.
Detailed Explanation
You want names for log levels or permission bits. Go has no enum keyword. You write a const block and let iota fill in the numbers. The first line in the block gets 0, the next 1, and so on. A blank line does not reset it; a new const ( block does.
The value is the line index, not the number of identifiers. const ( A = iota; B; C ) is 0, 1, 2 because B and C repeat the previous expression. That repetition is the actual feature: you write the expression once (1 << iota, iota + 1, iota * 10) and every following line re-evaluates it with a larger iota.
Skip and jump. _ = iota consumes a value you do not want to export. iota + 1 starts at 1. You can assign an explicit number on one line; iota still advances, so the next implicit line uses the next index, not the explicit number plus one. That last point is the usual surprise.
Typed constants with iota. type Level int plus const ( Info Level = iota; Warn; Error ) gives you a named type. The compiler will not pass a raw int where a Level is required. You still do not get exhaustiveness checks: switch on a Level will not fail to compile if you omit a case. For that, keep a test or a default that logs.
Bit flags. const ( Read = 1 << iota; Write; Exec ) produces 1, 2, 4. Combine them with |. This is the C-style flags pattern, with the same caveat: the zero value is "no bits," so reserve 0 as None if callers need to name it.
What it costs. Nothing at runtime. The cost is readability. A block that mixes explicit numbers, blank identifiers, and clever expressions becomes a puzzle. Keep one expression shape per block. If the values are not a sequence or a shift, write the numbers out and skip iota.
Code Examples
package main
import "fmt"
const (
Info = iota // 0
Warn // 1
Error // 2
)
func main() {
fmt.Println(Info, Warn, Error)
}type Perm uint
const (
Read Perm = 1 << iota // 1
Write // 2
Exec // 4
)
func canWrite(p Perm) bool { return p&Write != 0 }const (
_ = iota // skip 0
Monday
Tuesday
Wednesday
)
const (
KB = 1 << (10 * iota) // 1
MB // 1 << 10
GB // 1 << 20
)Common Gotchas
An explicit value does not reset `iota`
after `A = iota; B = 10; C` the value of `C` is 2 (the third line's `iota`), not 11. Start a new block if the sequence changes.
A named type is not an enum
any `Level(99)` converts. Validate at the boundary if the set is closed.
Each `const (` block has its own `iota` starting at 0
two blocks both start at 0 unless you write a different expression.
`iota` is only legal in `const` declarations
it is not a general counter you can use in functions.