如何创建枚举并对其进行迭代 [英] How to create an enum and iterate over it

查看:61
本文介绍了如何创建枚举并对其进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Go中复制Java枚举.我想定义一个枚举,然后对其进行迭代以进行一些验证.在Java中是这样的

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
}

在Golang中是否有类似的方法可以实现这一点,我在考虑使用结构,但我认为这不是最好的方法.

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.

有什么想法吗?

推荐答案

Go与Java的Enums等效,但通常 iota 在您要创建类似于枚举"的菜单时会派上用场.常数.

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
}

另请参阅:转到Wiki:Iota

有关 iota 的高级用法和技巧,请参见以下答案:

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

使用iota定义const变量时如何跳过很多值?

使用iota枚举字符串常量

这篇关于如何创建枚举并对其进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆