Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readGo
#Go#Constants#Bitmask
3D illustration of binary bit flags 1, 2, 4, 8 shifting upward with glowing iota counter increments

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

  • iota resets to 0 at the start of each const block and increments per ConstSpec line, not per identifier.
  • A declaration without an expression repeats the previous expression list verbatim, with the new iota value substituted.
  • _ skips a value, leaving a gap in the numbering that is still counted by iota.
  • Two identifiers on one line share one iota value: A, B = iota, iota+10 gives A = 0, B = 10.
  • 1 << iota produces 1, 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.
  • iota cannot appear outside a constant declaration: var x = iota is a compile error.
  • Go has no string enums; the String() method, usually generated by stringer, is how an iota enum prints its name.

Basic syntax and type signatures

go
// 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 )
go
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

PatternValuesUse
A = iota0, 1, 2, ...plain enumeration
A = iota + 11, 2, 3, ...enums that reserve 0 for unknown
A = iota * 1000, 100, 200, ...groups of ranges
A = 1 << iota1, 2, 4, 8, ...bit flags
A = 1 << (10 * (iota + 1))1024, 1<<20, 1<<30unit scales
A, B = iota, iota + 10(0,10), (1,11), ...parallel sequences
_ = iota as the first linenext member starts at 1skip zero
A = iota; _; C0, 1 skipped, 2intentional 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()

go
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

go
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

go
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

go
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:

go
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

go
// 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 symptomCauseFix
cannot use iota outside constant declarationiota in a var, expression statement, or returnmove it into a const block
missing init expr for Afirst spec in a block has no valuegive the first one a value
Values shifted by onea leading blank or _ line not accounted forcount lines; write a value test
Values shifted by a factorthe expression uses iota twicesimplify the expression
constant 256 overflows uint8too many flags for the underlying typewiden to uint16/uint32
A flag silently never matchesp&flag != 0 with a multi-bit maskuse p&flag == flag
String() panics with index out of rangea gap in the enum being indexed into an arrayuse a switch, or include the gap
Generated stringer output is wrongthe const block changed after generationre-run go generate
Two enums cannot be compareduntyped constants without a named typedeclare type X int and type the first constant
Old records decode to the wrong membermember order changedpin 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 tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.