Go: iota

Iota is a basic tool for enumerated constants.

Basics

The predeclared iota identifier resets to 0 whenever the word const appears in the source code and increments after each const specification:

const (
        C0 = iota
        C1 = iota
        C2 = iota
)
fmt.Println(C0, C1, C2) // "0 1 2"

This can be simplified to

const (
        C0 = iota
        C1
        C2
)

In a parenthesized const declaration expressions can be implicitly repeated—this indicates a repetition of the preceding expression.

Start at 1

const (
        C1 = iota + 1
        C2
        C3
)
fmt.Println(C1, C2, C3) // "1 2 3"

Skip value

const (
        C1 = iota + 1
        _
        C3
        C4
)
fmt.Println(C1, C3, C4) // "1 3 4"

Enumeration

type Suite int

const (
        Spades Suite = iota
        Hearts
        Diamonds
        Clubs
)

func (s Suite) String() string {
        return [...]string{"Spades", "Hearts", "Diamonds", "Clubs"}[s]
}

See Define an enumeration (enum) with a string representation for more details on how to create and use enumerations in Go.

Comments

Be the first to comment!