Go Enums: Usage Guide & Examples

In Go language, there is no built-in enumeration type, but constants can be used to simulate enumerations. A constant group is a set of related constant values, where their values can be different, but the type must be consistent.

Here is an example of simulating an enumeration using a constant group.

package main

import "fmt"

type Color int

const (
    Red    Color = iota // 0
    Blue               // 1
    Green              // 2
)

func main() {
    color := Red
    fmt.Println(color) // 输出: 0

    color = Blue
    fmt.Println(color) // 输出: 1

    color = Green
    fmt.Println(color) // 输出: 2
}

In this example, we defined a Color type and then used a constant group to define three colors. Iota is a special constant in the Go language that represents continuously increasing values, starting from 0.

Then we can use a variable of type Color to represent a color, such as color := Red. By outputting the value of the variable, we can see the corresponding integer value for each color.

It is worth noting that, although constant groups can simulate enums, in Go language constant groups are still concrete numerical values. Therefore, when comparing two enum values, == should be used for comparison.

bannerAds