英文:
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
有人可以帮助我吗?
英文:
I've looked at the various official sources for how to do this but I can't find it. Imagine you have the following enum (I know golang doesn't have enums in the classic sense):
package main
import "fmt"
type LogLevel int
const (
Off LogLevel = iota
Debug
)
var level LogLevel = Debug
func main() {
fmt.Printf("Log Level: %s", level)
}
The closest I can get with the above %s
, which gives me:
Log Level: %!s(main.LogLevel=1)
I would like to have:
Log Level: Debug
Can anyone help me?
答案1
得分: 9
你可以使用一个工具来生成支持代码,但不能直接在语言中实现。这个工具是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]]
}
英文:
You can't directly within the language, but there's a tool for generating the supporting code: golang.org/x/tools/cmd/stringer
From the example in the stringer
docs
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
Would produce code like
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]]
}
答案2
得分: -3
这对我有效:
level_str = fmt.Sprintf("%s", level)
英文:
This works for me:
level_str = fmt.SPrintf("%s", level)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论