如何使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}

You need to make the field exported,ie you may declare the struct as

type MyStruct struct {
    Field MyEnum
}

Here is a sample program with exported and unexported fields

Code

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 {
    Field1 MyEnum
    field2 MyEnum
}

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

Output

Foo
&{Foo 2}
&{Field1:Foo field2:2}
&main.MyStruct{Field1:1, field2:2}

Here is play link : https://play.golang.org/p/7knxM4KbLh