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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With