Home >Backend Development >Golang >How Can I Retrieve the Name of a Go Enum Without Manually Defining a `String()` Method?

How Can I Retrieve the Name of a Go Enum Without Manually Defining a `String()` Method?

DDD
DDDOriginal
2024-12-07 01:59:151016browse

How Can I Retrieve the Name of a Go Enum Without Manually Defining a `String()` Method?

Is it possible to get Enum name without adding String() method in Golang

In Go, to get the name of an enum, it is typically necessary to define a func (TheEnum) String() string method. However, this can be tedious, especially if there are many enums.

One alternative is to use Go's stringer tool from the standard tools package. This can be done by running the following command in the same directory as your enum definition:

stringer -type=Pill

This will create a file containing a definition of a func (Pill) String() string method.

package painkiller

type Pill int

const (
    Placebo Pill = iota
    Aspirin
    Ibuprofen
    Paracetamol
    Acetaminophen = Paracetamol
)

Running the stringer command:

stringer -type=Pill

Creates the following file:

// Code generated by "stringer -type=Pill"; DO NOT EDIT.

package painkiller

import "strconv"

func (p Pill) String() string {
    switch p {
    case Placebo:
        return "Placebo"
    case Aspirin:
        return "Aspirin"
    case Ibuprofen:
        return "Ibuprofen"
    case Paracetamol:
        return "Paracetamol"
    case Acetaminophen:
        return "Acetaminophen"
    }
    return "Pill(" + strconv.FormatInt(int64(p), 10) + ")"
}

This method can then be used to get the name of an enum, for example:

fmt.Println(Pill(3).String()) // Paracetamol

The stringer tool can be used with the go generate command in Go 1.4 to automatically generate a func (TheEnum) String() string method for each enum.

The above is the detailed content of How Can I Retrieve the Name of a Go Enum Without Manually Defining a `String()` Method?. 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