0

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 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Yeah, I know what Go has't enums like in Java. I map Java enums on html-select(ex. sex select, with 3 values: male, female, not choosen) and this is conveniently. In Go I can't do same thing. How I can work with html select values? String values are hard to validate against enums.
@Fire, Why is it hard? switch (sex) { case "male": ....; case "female": ...; case "unidentified": ...; default /* Produce an error */ }
@Fire, alternatively, just do what I proposed: use a map (though to me, a simple switch statement appears to be way superior).
One good argument for enums is that they provide static guarantees that maps+constants don't--namely, that all properties of the enum must be defined (in this case, that a new constant must have a corresponding entry in the map). This would prevent a silly mistake like adding a value in the const decl and forgetting to add it to the map.
@9us, yes and no. You take for granted that your statement is true but not everyone thinks the same way. See this for an example (this thread also contains a link to a discussion of the proposal of adding sum types to Go2).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.