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

Fire :

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.

kostix :

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related