dqnhfbc3738 2016-02-25 14:54
浏览 372


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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?
  • ¥15 Ubuntu20.04.4.LTS系统如何下载安装VirtualBox虚拟机?