How to make Go print enum fields as string?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)