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

  • A+
Category:Languages

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  {     ...  } 

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: