Go 中的可打印枚举

Fra*_*sco 4 string enums go

在某些情况下,使用人类可读的枚举字符串表示形式可以方便用户交互和调试。到目前为止,我想出的最好的办法是:

type ElementType int

const (
    Fire = ElementType(iota)
    Air
    Water
    Earth
)

var elementTypeMap = map[ElementType]string{
    Fire: "The Fiery Fire",
    Air: "The Airy Air",
    Water: "The Watery Water",
    Earth: "The Earthy Earth",
}

func (el ElementType) String() string {
    return elementTypeMap[el]
}
Run Code Online (Sandbox Code Playgroud)

上面的内容允许我使用枚举并将其作为 int 传递,保持其标准性能,并在任何地方轻松打印其字符串表示形式。唯一的缺点是,如果您有许多枚举类型,则会增加大量样板代码:我很乐意避免它。

有没有一种方法(最好是惯用的方法)来减少上面的样板代码?

Den*_*ret 5

这看起来更干燥(而且更快):

type ElementType int

const (
    Fire = ElementType(iota)
    Air
    Water
    Earth
)

var elementnames = [...]string {
    "The Fiery Fire",
    "The Airy Air",
    "The Watery Water",
    "The Earthy Earth"
}

func (el ElementType) String() string {
    return elementnames[el]
}
Run Code Online (Sandbox Code Playgroud)

请注意,关于 golang-nuts 进行了一次讨论,讨论是否提供通用解决方案来为枚举常量分配名称,据我所知,这没有必要(请参阅https://groups.google.com/forum/# !topic/golang-nuts/fCdBSRNNUY8 )。