a shot of dev knowledge

Related tags

What is an enum in Golang?

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

RELATED COURSES
View all Courses
Related Courses
Related Courses
View all Courses

Keep Exploring