-
Notifications
You must be signed in to change notification settings - Fork 18.4k
Description
Currently, the stringer tool generates the method func (t Type) String() string
to get the string name of an enum value.
In several projects I have had the need of exactly the opposite: get the enum value from the string name (for example when parsing a flag or when reading a configuration file).
I have ended up using a switch
or a map
, but I don't like it as I have to manually maintain it when values are added/changed/deleted. So the next step is to auto-generate it, just like the stringer tool does.
I was wondering if adding this functionality to stringer
would be adequate for you guys. In my opinion, it seems pretty convenient and fits very well in that tool. I am sure there will be other people in the same situation than me that will benefit from it.
A possible signature for the generated function could be:
func <Type>FromString(s string) (<Type>, error) {...}
// Or
func <Type>String(s string) (<Type>, error) {...}
For example, if the type is Pill
the function would be
func PillFromString(s string) (Pill, error) {...}
// Or
func PillString(s string) (Pill, error) {...}
The implementation could leverage the same variable the stringer tool already generates (a string or a map, depending on the number of runs found in the enum values). This requires a deeper reasoning (maybe a switch
is the best option here)
Having an error
as a second return value is needed to notify about strings that do not belong to the enum type.
The code to add is relatively simple and I can contribute with the needed changes.
Before doing that, I would like to hear your opinions/suggestions and know if you finally agree.