An enum, or enumerator, is a data type consisting of a set of named constant values. Enums are a powerful feature with a wide range of uses. However, in Golang, they’re implemented quite differently than most other programming languages. In Golang, we use a predeclared identifier, iota
, and the enums are not strictly typed.
A typical enum Direction
with four possible values can be defined as:
type Direction int
const (
North Direction = iota
South
East
West
)
The iota
is a built-in, predeclared identifier that represents successive untyped integer constants. Its value is the index of the respective ConstSpec
in that constant declaration – it starts at zero.
Read more about
iota
here https://go.dev/ref/spec
We declare a simple enum called Direction
with four possible values: North
, South
, East
, and West
.
package mainimport "fmt"type Direction intconst (North Direction = iotaSouthEastWest)func main() {// Declaring a variable myDirection with type Directionvar myDirection DirectionmyDirection = Westif (myDirection == West) {fmt.Println("myDirection is West:", myDirection)}}
Free Resources