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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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我可以得到的最接近的数字,这给了我:

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

我想拥有:

1
Log Level: Debug

谁能帮我?

  • 是否有可能重复获取Enum名称而不在Golang中创建String()

您不能直接在该语言中使用,但是有一个用于生成支持代码的工具:golang.org/x/tools/cmd/stringer

stringer文档中的示例

1
2
3
4
5
6
7
8
9
type Pill int

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

会产生像

1
2
3
4
5
6
7
8
9
10
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]]
}
  • 这是非常脆弱的代码,不能解决DRY问题。 如果您要朝那个方向前进,最好也有一个显式且简单的String()方法,并为每个const设置一个开关。
  • @ZephaniahGrunschlag:这就是本示例的工作; 它生成一个简单的String方法,除非您不必自己维护它,甚至不必查看生成的代码。 在go项目中使用stringer包是相当普遍的。 它不是要创建一个真正的枚举,String()输出并不意味着要进行任何比较或验证,它只是一种创建人类可读输出的便捷方法。 您不需要拒绝答案,因为您不喜欢Go社区选择的解决方案。

这对我有用:


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