Golang的枚举类型能否像Java的枚举类型一样实现相同的行为?

huangapple go评论89阅读模式
英文:

Can Golang enum do same behavior like Java's enum?

问题

Java的枚举类型有一个有用的方法'valueOf(string)',它可以根据名称返回对应的枚举常量。

例如:

enum ROLE {
  FIRST("First role"),
  SECOND("Second role");

  private final String label;

  private ROLE(String label) {
    this.label = label;
  }

  public String getLabel() {
    return label;
  }
}

// 在代码的其他地方,我们可以这样使用:
ROLE.valueOf("FIRST").getLabel(); // 返回"First role"

这种行为在某些情况下非常有用,比如在HTML表单提交到服务器后,我们需要将字符串表示转换为真正的枚举类型。

请问Go语言是否可以实现相同的行为?如果有代码示例就更好了。

英文:

Java's enums have usefull method 'valueOf(string)' what return const enum member by it name.
Ex.

enum ROLE {
  FIRST("First role"),
  SECOND("Second role")

  private final String label;

  private ROLE(label String) {
    this.label = label;
  }

  public String getLabel() {
    return label;
  }
}
// in other place of code we can do:
ROLE.valueOf("FIRST").getLabel(); // get's "First role"

This behavior usefull for, for example, after html form's select submits to server. We have string representation what need to convert into real enum.

Can someone tell, can golang do same behavior? Code examples are welcome.

答案1

得分: 4

不。Go语言没有枚举类型。所以你需要使用一个单独的映射表:

const (
    First = iota
    Second
)

var byname = map[string]int {
    "First": First,
    "Second": Second,
}

如果你需要有很多这样的常量,可以考虑使用代码生成

但实际上,我没有看到你想要的功能的真正原因:常量在源代码中的名称已经是文本,因此它们已经相当自描述了。所以“在运行时获取与文本字符串相关联的数字”的唯一合理用例是解析一些数据/输入,而这个问题可以通过重新表述问题来明显地使用查找映射表来解决。

英文:

No. And Go does not have enums.

So you'll need to use a separate map:

const (
    First = iota
    Second
)

var byname = map[string]int {
    "First": First,
    "Second": Second,
}

If you need to have lots of such constants, consider using code generation.

But actually I fail to see a real reson for a feature you want: constants are pretty much self-describing as in the source code their names are already text. So the only sensible use case for the "get a number associated with a textual string at runtime" is parsing some data/input, and this one is the case for using a lookup map—which is apparent once you reformulate the problem like I did.

huangapple
  • 本文由 发表于 2016年2月25日 22:54:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/35630698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定