如何在 Go 中打印 "enum" 的字符串表示形式?

How to print the string representation of an "enum" in Go?

我查看了各种官方资源以了解如何执行此操作,但找不到。假设您有以下枚举(我知道 golang 没有传统意义上的枚举):

package main

import "fmt"

type LogLevel int

const (
    Off LogLevel = iota
    Debug
)

var level LogLevel = Debug

func main() {
    fmt.Printf("Log Level: %s", level)
}

我能得到的最接近上面的 %s,这给了我:

Log Level: %!s(main.LogLevel=1)

我想要:

Log Level: Debug

谁能帮帮我?

你不能直接在语言中,但是有一个工具可以生成支持代码:golang.org/x/tools/cmd/stringer

来自 stringer 文档中的示例

type Pill int

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

会生成类似

的代码
const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"

var _Pill_index = [...]uint8{0, 7, 14, 23, 34}

func (i Pill) String() string {
    if i < 0 || i+1 >= Pill(len(_Pill_index)) {
        return fmt.Sprintf("Pill(%d)", i)
    }
    return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}

这对我有用:

level_str = fmt.SPrintf("%s", level)