Home >Backend Development >Golang >How Can I Get Go Enum Names Without Writing Explicit String Conversions?

How Can I Get Go Enum Names Without Writing Explicit String Conversions?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 07:45:17730browse

How Can I Get Go Enum Names Without Writing Explicit String Conversions?

Getting Enum Names in Go Without Explicit String Conversion

In Go, enums are typically implemented as constants assigned integer values. However, accessing the enum name without explicitly creating a String() method can be cumbersome.

Consider this example:

const (
    MERCURY = 1
    VENUS = iota
    EARTH
    MARS
    JUPITER
    SATURN
    URANUS
    NEPTUNE
    PLUTO
)

To obtain the enum name, one may define a String() method for each enum value, leading to repetitive retyping or code generation. Is there an alternative?

Using the Stringer Tool

Go provides the stringer tool, which automates the creation of String() methods for constants. By executing the following command in the same directory as the code above:

stringer -type=MERCURY

a new file mercury_string.go is generated in the package context, containing:

func (MERCURY) String() string

This method allows retrieving the enum name conveniently and reduces the need for explicit string conversion.

Additional Note:

While this technique solves the issue of obtaining enum names without explicit String() methods, keep in mind that it requires the use of an external tool and may not always be feasible in certain scenarios.

The above is the detailed content of How Can I Get Go Enum Names Without Writing Explicit String Conversions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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