Home > Backend Development > Golang > How to Get Go Enum Names Without a String() Function?

How to Get Go Enum Names Without a String() Function?

DDD
Release: 2024-11-27 09:10:09
Original
301 people have browsed it

How to Get Go Enum Names Without a String() Function?

How to Obtain Enum Names Without the String() Function?

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
)
Copy after login

To generate the String() function for this enum, execute the following command in the terminal:

stringer -type=Planet
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template