Constants name values that do not change, and iota can count related constants.

iota Inside a Go constant block, `iota` starts at zero and increases by one on each line.

Constants and Iota

status
constants_iota.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

const (
	StatusNew = iota
	StatusActive
	StatusDone
)

func main() {
	var status = StatusActive
	label := ""

	if status == StatusNew {
		label = "new"
	} else if status == StatusActive {
		label = "active"
	} else {
		label = "done"
	}

	fmt.Println("status=", status)
	fmt.Println("label=", label)
}
package main

import "fmt"

const (
	StatusNew = iota
	StatusActive
	StatusDone
)

func main() {
	var status = StatusNew
	label := ""

	if status == StatusNew {
		label = "new"
	} else if status == StatusActive {
		label = "active"
	} else {
		label = "done"
	}

	fmt.Println("status=", status)
	fmt.Println("label=", label)
}
package main

import "fmt"

const (
	StatusNew = iota
	StatusActive
	StatusDone
)

func main() {
	var status = StatusDone
	label := ""

	if status == StatusNew {
		label = "new"
	} else if status == StatusActive {
		label = "active"
	} else {
		label = "done"
	}

	fmt.Println("status=", status)
	fmt.Println("label=", label)
}
  1. status ← 1, StatusActive ← 1, label ← ""

    11func main() {12  var status→ 1 = StatusActive→ 1 //@status=StatusNew, StatusDone13  label→ "" := ""
  2. label ← "active"

    16  label = "new"17} else if status1 == StatusActive1 {18  label→ "active" = "active"19} else {
  3. fmt.Println("status=", status)

    23  fmt.Println("status=", status1)24  fmt.Println("label=", label"active")25}
    outputstatus= 1
    label= active
  1. status ← 0, StatusNew ← 0, label ← ""

    11func main() {12  var status→ 0 = StatusNew→ 013  label→ "" := ""
  2. label ← "new"

    15if status0 == StatusNew0 {16  label→ "new" = "new"17} else if status == StatusActive {
  3. fmt.Println("status=", status)

    23  fmt.Println("status=", status0)24  fmt.Println("label=", label"new")25}
    outputstatus= 0
    label= new
  1. status ← 2, StatusDone ← 2, label ← ""

    11func main() {12  var status→ 2 = StatusDone→ 213  label→ "" := ""
  2. label ← "done"

    18  label = "active"19} else {20  label→ "done" = "done"21}
  3. fmt.Println("status=", status)

    23  fmt.Println("status=", status2)24  fmt.Println("label=", label"done")25}
    outputstatus= 2
    label= done

Follow the Labels

  1. StatusNew is 0.
  2. StatusActive is 1.
  3. StatusDone is 2.
  4. status starts as StatusActive, so its number is 1.
  5. The matching label is active, so the program prints status= 1 and label= active. | status value | number | label | | --- | --- | --- | | StatusNew | 0 | new | | StatusActive | 1 | active | | StatusDone | 2 | done |

Exercise: constants_iota.go

Reproduce label= active, then use the pinned status values StatusNew and StatusDone to predict each label.