Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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  {
    ... 
}
like image 404
Sergii Getman Avatar asked Dec 07 '22 13:12

Sergii Getman


1 Answers

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.

like image 176
Grzegorz Żur Avatar answered May 06 '23 05:05

Grzegorz Żur