dqy27359
2017-01-05 08:43
浏览 397
已采纳

如何使Go将枚举字段打印为字符串?

You print an enum that implements Stringer using "%v", it will print its string value. If you declare the same enum inside a struct and print the struct using "%v", it will print enum's numeric value. Is there a way to print the string value of a enum field?

Sample (https://play.golang.org/p/AP_tzzAZMI):

package main

import (
    "fmt"
)

type MyEnum int

const (
    Foo MyEnum = 1
    Bar MyEnum = 2
)

func (e MyEnum) String() string {
    switch e {
    case Foo:
        return "Foo"
    case Bar:
        return "Bar"
    default:
        return fmt.Sprintf("%d", int(e))
    }
}

type MyStruct struct {
    field MyEnum
}

func main() {
    info := &MyStruct{
        field: MyEnum(1),
    }
    fmt.Printf("%v
", MyEnum(1))
    fmt.Printf("%v
", info)
    fmt.Printf("%+v
", info)
    fmt.Printf("%#v
", info)
}

Prints:

Foo
&{1}
&{field:1}
&main.MyStruct{field:1}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题