Understanding Go Constants and the iota Enumerator

Constants represent fixed values that remain unchanged throughout the lifetime of a program. In Go, declaring a constant differs only slightly from declaring a variable; you replace the var keyword with const, and an initial value is mandatory at the point of definition.

const pi = 3.14
const g = 9.98

Once declared, these identifiers cannot be reassigned or altered during program execution.

You can also group multiple constant definitions into a block:

const (
    pi = 3.14
    g  = 9.98
)

Within a grouped const declaration, if you omit the value for a constant, it automatically inherits the value from the previous line.

package main

import "fmt"

func main() {
    const (
        x = 42
        y
        z
    )
    fmt.Println(x, y, z)
}

The built-in identifier iota serves as a special auto-incremetning counter available only inside const blocks. It resets to 0 whenever a const keyword appears and increments by one for each successive constant declaration inside that block. This makes it particularly useful when defining enumerations.

const (
    first  = iota // 0
    second         // 1
    third          // 2
    fourth         // 3
)

Practical iota Patterns

Skip a position using the blank identifier:

const (
    v1 = iota // 0
    v2        // 1
    _         // 2 (skipped)
    v4        // 3
)

Interleave explicit values with iota:

const (
    s1 = iota   // 0
    s2 = 100    // 100
    s3 = iota   // 2
    s4          // 3
)
const s5 = iota // 0 (iota resets with each const)

Each const block starts a fresh iota count.

Express storage magnitudes using bit shifting:

const (
    _  = 1 << (10 * iota)
    KB = 1 << (10 * iota)
    MB = 1 << (10 * iota)
    GB = 1 << (10 * iota)
    TB = 1 << (10 * iota)
    PB = 1 << (10 * iota)
)

Combine multiple iota expressions on a single line:

const (
    one, two   = iota + 1, iota + 2 // 1, 2
    three, four                    // 2, 3
    five, six                      // 3, 4
)

By shifting bits, each constant multiplies the preceding value by 1024, generating a clean powers-of-two scale.

Tags: Go constants iota enumerations bit-shifting

Posted on Fri, 09 Oct 2026 16:47:53 +0000 by Jason Batten