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

huangapple go评论86阅读模式
英文:

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 = &quot;PlaceboAspirinIbuprofenParacetamol&quot;

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

func (i Pill) String() string {
	if i &lt; 0 || i+1 &gt;= Pill(len(_Pill_index)) {
		return fmt.Sprintf(&quot;Pill(%d)&quot;, 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(&quot;%s&quot;, level)

huangapple
  • 本文由 发表于 2015年5月12日 04:45:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/30177344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定