How to create an enum and iterate over it

自古美人都是妖i 提交于 2021-02-04 19:59:54

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/64178176/how-to-create-an-enum-and-iterate-over-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!