What is idiomatic way to get string representation of enum in Go?

Issue

If I have an enum:

type Day int8

const (
    Monday Day = iota
    Tuesday
    ...
    Sunday
)

What is more natural Go way to get string of it?

fucntion:

func ToString(day Day) string {
   ...
}

or method

func (day Day) String() string  {
    ... 
}

Solution

The second one is more idiomatic because it satisfies Stringer interface.

func (day Day) String() string  {
    ... 
}

We declare this method on the Day type not *Day type because we are not changing the value.

It will enable you to write.

fmt.Println(day)

and get the value produced by String method.

Answered By – Grzegorz ┼╗ur

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.