2016-02-25 14:54
浏览 194


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.

图片转代码服务由CSDN问答提供 功能建议

Java的枚举具有有用的方法'valueOf(string)',它通过其名称返回const枚举成员。 Ex。< / p>

 枚举ROLE {
私有ROLE  (标签字符串){
 this.label = label; 
 public String getLabel(){
ROLE.valueOf( “FIRST”)getLabel();  //获得“第一个角色” 

例如,在html表单的选择提交到服务器后,此行为很有用。 我们有字符串表示形式,需要将什么转换为真实的枚举。

有人可以告诉,golang可以做同样的事情吗? 欢迎使用代码示例。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyin6188 2016-02-25 15:40

    No. And Go does not have enums.

    So you'll need to use a separate map:

    const (
        First = iota
    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.

    点赞 打赏 评论

相关推荐 更多相似问题