typestar

Constants and iota in Go

Untyped constants and iota, which is how Go writes an enum.

type State int

const (
    StateIdle State = iota
    StateRunning
    StateDone
)

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

func (s State) String() string {
    names := [...]string{"idle", "running", "done"}
    if s < 0 || int(s) >= len(names) {
        return "unknown"
    }
    return names[s]
}

How it works

  1. iota counts from zero within a const block.
  2. The blank identifier skips a value, so KB starts at 1 << 10.
  3. A String method turns the constant into something printable.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
271
Tokens
75
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 56 seconds.

Type this snippet

Step 3 of 5 in Variables & types, step 3 of 30 in Language basics.

← Previous Next →