Understand the contract

A Go constant names a value known at compile time. Declare one with const when a value must stay fixed, such as a maximum retry count. Constants can represent numeric, string and boolean values. A slice, map or value returned by an ordinary function cannot be declared as a constant.

iota supplies successive integer values within a constant declaration group. It starts at zero and advances with each constant specification. A named integer type lets the example distinguish a State from an arbitrary int in API signatures, while the constants provide readable names for the expected values.

Work through the example

The example prints 0 1 2. Pending, Running and Done have type State because the following specifications repeat the first expression and type. An untyped constant such as const limit = 10 can be used where its value is representable by the required numeric type.

package main

import "fmt"

type State int

const (
    Pending State = iota
    Running
    Done
)

func main() { fmt.Println(Pending, Running, Done) }

Watch this boundary

Inserting a constant in the middle of an iota sequence changes later values. Do not casually use that sequence as a durable database or network representation. Give external protocol values explicit numbers or strings and validate incoming values; a named type alone does not restrict all possible integers.

Practice with a changed input

Add a String method later in the methods lesson. For now, insert a new state between Running and Done and observe the changed numeric output.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services