dqnhfbc3738
dqnhfbc3738
2016-02-25 14:54

Golang枚举可以做与Java枚举相同的行为吗?

已采纳

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条回答

  • douyin6188 douyin6188 5年前

    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.

    点赞 评论 复制链接分享