-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: Go 2: iota for strings (useful for enums) #32176
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
While I like the idea, what would |
If the type is not specified it becomes a number just like today. I agree that a sperate name would be better, maybe I think the last option ( |
Why declare enum values as strings? Generally, you just need the values to be unique and simple, so integers are fine. If you need to represent them as strings, you can use https://godoc.org/golang.org/x/tools/cmd/stringer. |
Because printing strings is easier than ints. I don't need a conversion function or a mapping table to print my errors and understand them. |
This is precisely what |
Making a new predeclared identifier doesn't introduce backward compatibility problems. @mvdan is also right that code generation with the stringer command already takes care of this. |
I would have sometimes liked a feature such like this, but more often than not, I wouldn't want the string to match my constant name exactly. Worse, if one changes a constant's name, for instance when changing whether a constant is exported or not, the string would change, too, which seems not a desirable feature. It also seems a bit unfortunate to "reuse" But most importantly, we do have the I'm not in favor of this proposal. |
it seems to me that the most natural way to do it would be to allow
which keeps iota unchanged and adds the cast. This compiles now and gives FRIDAY == "\x04", what is new is making the meaning of string in this context be "itoa". |
Thanks, but we already have the stringer tool, and that seems like the right tool for this job. |
Problem
We can write code like this:
But not like this:
Proposal
Make
iota
return strings with the same value as the const name.Example, this:
Is equal to this:
Why?
Simple, it makes writing code that use such enums easier, less boring and less error prone.
One good example is writing code that deals with errors:
Compatibility
Current Golang, gives this error when trying to compile code like the one proposed:
cannot convert 1 (type untyped number) to type string
As such I don't think that any old code will become incompatible.
The text was updated successfully, but these errors were encountered: