Trusted answers to developer questions

What is an enum in Golang?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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.

Syntax

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.

Example

We declare a simple enum called Direction with four possible values: North, South, East, and West.

package main
import "fmt"
type Direction int
const (
North Direction = iota
South
East
West
)
func main() {
// Declaring a variable myDirection with type Direction
var myDirection Direction
myDirection = West
if (myDirection == West) {
fmt.Println("myDirection is West:", myDirection)
}
}

RELATED TAGS

golang
enum
enumerate
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?