Go enumerations, achieved through iota, lack an explicit String() function, limiting the direct retrieval of enum names as strings. This article explores alternatives to overcome this limitation and obtain enum names without retyping labels.
One possible solution is utilizing the stringer tool from the standard tools package. This tool automates the generation of a String() function for your enum type.
For instance, consider the following enum definition:
const ( MERCURY = 1 VENUS = iota EARTH MARS JUPITER SATURN URANUS NEPTUNE PLUTO )
To generate the String() function for this enum, execute the following command in the terminal:
stringer -type=Planet
This command will create the file planet_string.go in the current working directory, containing the generated function. The function can now be used to obtain planet names as strings.
Additionally, you can consider using struct-based or string-based constants. While these approaches require retyping labels once, they provide greater flexibility in certain scenarios.
The above is the detailed content of How to Get Go Enum Names Without a String() Function?. For more information, please follow other related articles on the PHP Chinese website!