Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an enum and iterate over it

Tags:

loops

enums

go

I'm trying to replicate the Java enums in Go. I would like to define an enum and then iterate over it to do some validations. Something like this in java

public enum Direction {
   NORTH,
   NORTHEAST,
   EAST,
   SOUTHEAST,
   SOUTH,
   SOUTHWEST,
   WEST,
   NORTHWEST
}

And the I would like to iterate over it, like this:

for (Direction dir : Direction.values()) {
  // do what you want
}

Is there a similar way to achieve this in Golang, I'm thinking in using structs but I don't think it's the best way.

Any ideas?

like image 989
rasilvap Avatar asked Dec 30 '22 20:12

rasilvap


1 Answers

Go doesn't have an equivalent to Java's Enums, but usually iota comes handy when you want to create "enum-like" constants.

Your example may be described like this:

type Dir int

const (
    NORTH Dir = iota
    NORTHEAST
    EAST
    SOUTHEAST
    SOUTH
    SOUTHWEST
    WEST
    NORTHWEST
    dirLimit // this will be the last Dir + 1
)

And then to iterate over all directions (try it on the Go Playground):

for dir := Dir(0); dir < dirLimit; dir++ {
    // do what you want
}

Also see: Go Wiki: Iota

For advanced use and tricks with iota, see these answers:

How to skip a lot of values when define const variable with iota?

Enumerating string constants with iota

like image 186
icza Avatar answered Jan 12 '23 22:01

icza