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
Release: 2024-12-07 01:59:15
Original
1003 people have browsed it

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

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

Running the stringer command:

stringer -type=Pill
Copy after login
Copy after login

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

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

fmt.Println(Pill(3).String()) // Paracetamol
Copy after login

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!

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