How to get Go to print enum fields as a string?

You print an enumeration that implements Stringer with "% v", it will output its string value. If you declare the same enumeration inside the structure and print the structure using "% v", it will print the numeric number of enumerations. Is there a way to print the string value of an enum field?

Example ( 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\n", MyEnum(1)) fmt.Printf("%v\n", info) fmt.Printf("%+v\n", info) fmt.Printf("%#v\n", info) } 

Print

 Foo &{1} &{field:1} &main.MyStruct{field:1} 
+7
enums go
source share
1 answer

You need to create the exported field, i.e. you can declare the structure as

 type MyStruct struct { Field MyEnum } 

Here is an example program with exported and unexported

The 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\n", MyEnum(1)) fmt.Printf("%v\n", info) fmt.Printf("%+v\n", info) fmt.Printf("%#v\n", info) } 

Exit

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

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

+5
source share

All Articles