Go iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.

iota is a predeclared constant that exists only inside a const block. It starts at 0 on the first ConstSpec of the block and increments by one for every following spec, so the sequence of const lines is the sequence of values. The identifier itself is untyped when used alone, typed when the surrounding declaration gives it a type, and usable anywhere a constant expression is allowed — which is what makes 1 << iota the standard way to write bit flags and iota + 100 the standard way to start an enum at a specific number.
Quick Summary
iotaresets to 0 at the start of eachconstblock and increments perConstSpecline, not per identifier.- A declaration without an expression repeats the previous expression list verbatim, with the new
iotavalue substituted. _skips a value, leaving a gap in the numbering that is still counted byiota.- Two identifiers on one line share one
iotavalue:A, B = iota, iota+10givesA = 0, B = 10. 1 << iotaproduces1, 2, 4, 8, ...and is the canonical bitmask; combined with a named type it gives flags a method set.- Typed declarations (
const Sunday Weekday = iota) type every following member, so the enum is a distinct type rather than a pile of untyped integers. iotacannot appear outside a constant declaration:var x = iotais a compile error.- Go has no string enums; the
String()method, usually generated bystringer, is how an iota enum prints its name.
Basic syntax and type signatures
// Typed enumeration.
type Weekday int
const (
Sunday Weekday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)
// Starting at a different number, and skipping a value.
const (
Unknown Level = iota + 1 // 1
Low // 2
_ // 3 skipped
High // 4
)
// Bit flags.
type Permission uint8
const (
PermRead Permission = 1 << iota // 1
PermWrite // 2
PermExecute // 4
PermAdmin // 8
)
// Expressions that use iota more than once per line.
const (
KB = 1 << (10 * (iota + 1)) // 1024
MB // 1048576
GB // 1073741824
)func (d Weekday) String() string {
return [...]string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}[d]
}
func (p Permission) String() string {
if p == 0 {
return "none"
}
names := []struct {
bit Permission
name string
}{
{PermRead, "read"},
{PermWrite, "write"},
{PermExecute, "exec"},
{PermAdmin, "admin"},
}
out := ""
for _, n := range names {
if p&n.bit != 0 {
if out != "" {
out += "|"
}
out += n.name
}
}
return out
}Common iota patterns and their values
| Pattern | Values | Use |
|---|---|---|
A = iota | 0, 1, 2, ... | plain enumeration |
A = iota + 1 | 1, 2, 3, ... | enums that reserve 0 for unknown |
A = iota * 100 | 0, 100, 200, ... | groups of ranges |
A = 1 << iota | 1, 2, 4, 8, ... | bit flags |
A = 1 << (10 * (iota + 1)) | 1024, 1<<20, 1<<30 | unit scales |
A, B = iota, iota + 10 | (0,10), (1,11), ... | parallel sequences |
_ = iota as the first line | next member starts at 1 | skip zero |
A = iota; _; C | 0, 1 skipped, 2 | intentional gaps |
The gap row is worth internalizing: a skipped value still advances the counter, so C is 2 and not 1. Gaps are how a removed enum member keeps its number from being reused by a later addition.
Practical edge cases and deep dives
1. Typed enums, gaps, and String()
type Status int
const (
StatusUnknown Status = iota
StatusActive
StatusSuspended
_ // reserved: was StatusDeleted
StatusArchived
)
func (s Status) Valid() bool {
switch s {
case StatusUnknown, StatusActive, StatusSuspended, StatusArchived:
return true
default:
return false // includes the gap value 3
}
}
func (s Status) String() string {
switch s {
case StatusUnknown:
return "unknown"
case StatusActive:
return "active"
case StatusSuspended:
return "suspended"
case StatusArchived:
return "archived"
default:
return "invalid(" + strconv.Itoa(int(s)) + ")"
}
}
// Database boundary: parse the number, reject gaps.
func ParseStatus(n int) (Status, error) {
s := Status(n)
if !s.Valid() {
return StatusUnknown, fmt.Errorf("invalid status %d", n)
}
return s, nil
}Typing the constant is what makes the enum a distinct type: StatusActive cannot be passed where a Weekday is expected. The type does not protect the boundary, though — an untyped literal is assignable to a named integer type (var s Status = 2 compiles), and a value read from JSON arrives as a plain number, which is why ParseStatus exists to validate before anything switches on the value. The String() method turns logs and JSON into something readable; stringer generates exactly this switch from the const block, and a mismatch between the two is a silent source of wrong names.
2. Bit flags and the helpers that make them readable
type Permission uint8
const (
PermNone Permission = 0
PermRead Permission = 1 << iota // 1
PermWrite // 2
PermExec // 4
)
func (p Permission) Has(flag Permission) bool { return p&flag == flag }
func (p Permission) With(flag Permission) Permission { return p | flag }
func (p Permission) Without(flag Permission) Permission { return p &^ flag }
const editor = PermRead | PermWrite
func use() {
fmt.Println(editor.Has(PermRead)) // true
fmt.Println(editor.Has(PermExec)) // false
fmt.Println(editor.With(PermExec)) // 7
fmt.Println(editor.Without(PermWrite)) // 1
}Three details make flag sets correct. The type must be wide enough: uint8 holds eight flags, and a ninth silently fails to compile rather than overflowing. The Has check uses p&flag == flag so a multi-bit mask is tested as a whole — p&flag != 0 returns true for a partial match. The zero value is a meaningful "no permissions", which lets a struct field default to no access without initialization. PermNone Permission = 0 plus PermRead = 1 << iota on the next line gives PermRead the value 1, since iota counts lines: the first line is 0, the second is 1.
3. Unit scales and the exponent pattern
type ByteSize float64
const (
_ = iota // ignore the first value
KB ByteSize = 1 << (10 * iota) // 1024
MB // 1048576
GB // 1073741824
TB // 1099511627776
)
func (b ByteSize) String() string {
switch {
case b >= TB:
return fmt.Sprintf("%.2fTB", b/TB)
case b >= GB:
return fmt.Sprintf("%.2fGB", b/GB)
case b >= MB:
return fmt.Sprintf("%.2fMB", b/MB)
case b >= KB:
return fmt.Sprintf("%.2fKB", b/KB)
default:
return fmt.Sprintf("%dB", b)
}
}The leading _ = iota line is what makes KB use iota == 1 and therefore 1 << 10. Reordering the blank line, or adding a comment line, changes every value — comments do not count, but blank lines with a declaration do. This pattern is the standard one in go-humanize-style packages and in every codebase that defines its own size constants; it is also why those constants should be tested by value (if KB != 1024) rather than assumed.
4. Same-line rules and implicit repetition
const (
A, B = iota, iota + 10 // A=0 B=10
C, D // C=1 D=11
E, F // E=2 F=12
)
const (
X = iota * 2 // 0
Y // 2
Z // 4
)
const (
P = 1 << iota // 1
Q = 1 << iota // 2, spelled out
R // 4
S = "fixed" // iota is 3 here, unused
T // "fixed"
)The rule is that an omitted expression list repeats the previous list exactly, with the current iota substituted wherever it appears. In the S example, iota is still advancing but nothing in the expression uses it, so S and T are both "fixed" and a later U = iota would be 5. Mixing string constants into a numeric block is legal and almost always a mistake; the two kinds of constants should live in separate blocks so the numbering stays obvious.
const blocks also appear inside functions, where iota behaves the same way:
func retryDelays() []time.Duration {
const (
first = time.Second * (1 << iota) // 1s
second // 2s
third // 4s
)
return []time.Duration{first, second, third}
}5. Where iota does not work, and how to validate the numbers
// var x = iota // compile error: cannot use iota outside constant declaration
// const ( A int; B ) // compile error: missing init expr for A
type Mode uint8
const (
ModeFast Mode = iota
ModeSlow
ModeUnset Mode = 255 // explicit value: does not use iota
)
func ModeFromString(s string) (Mode, error) {
switch s {
case "fast":
return ModeFast, nil
case "slow":
return ModeSlow, nil
default:
return 0, fmt.Errorf("unknown mode %q", s)
}
}
// A test that catches renumbering:
func TestModeValues(t *testing.T) {
if ModeFast != 0 || ModeSlow != 1 {
t.Fatalf("mode values changed: fast=%d slow=%d", ModeFast, ModeSlow)
}
}iota produces constants with no stability guarantee beyond the order of the lines, so any value that crosses a process boundary — stored in a database, sent in a JSON payload, written into a config file — should be pinned by a test or given explicit values. The test is cheaper than the explicit values and catches the accidental reorder, which is the change most likely to reinterpret old data.
Common mistakes and compiler errors
| Error or symptom | Cause | Fix |
|---|---|---|
cannot use iota outside constant declaration | iota in a var, expression statement, or return | move it into a const block |
missing init expr for A | first spec in a block has no value | give the first one a value |
| Values shifted by one | a leading blank or _ line not accounted for | count lines; write a value test |
| Values shifted by a factor | the expression uses iota twice | simplify the expression |
constant 256 overflows uint8 | too many flags for the underlying type | widen to uint16/uint32 |
| A flag silently never matches | p&flag != 0 with a multi-bit mask | use p&flag == flag |
String() panics with index out of range | a gap in the enum being indexed into an array | use a switch, or include the gap |
Generated stringer output is wrong | the const block changed after generation | re-run go generate |
| Two enums cannot be compared | untyped constants without a named type | declare type X int and type the first constant |
| Old records decode to the wrong member | member order changed | pin values or test them |
The pattern that keeps an iota enum maintainable is to type the first constant, never reuse a removed number (leave a _), and keep the enum in one block that nothing else is appended to. The number is an implementation detail of the ordering; the name and the type are the API, and anything storage-facing needs an explicit value or a test that fails the moment the ordering moves.
Try matching browser tools
All toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
Go init Function: Package Initialization Order, Imports, and Side Effects
What runs before main, the order across imports and files, why init cannot return an error, and the sync.Once replacement that can be tested.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.