Is it possible to get the name Enum without creating String () in Golang

Is it possible to get the name Enum without creating func (TheEnum) String() string in Golang?

 const ( MERCURY = 1 VENUS = iota EARTH MARS JUPITER SATURN URANUS NEPTUNE PLUTO ) 

or is there a way to define constants "on the fly"? I found two ways struct and string , but both methods force us to repeat each label 1 more time (or copy-paste and quote or use the editor macro)

+6
enums go
source share
1 answer

AFAIK, you cannot do this without explicitly entering the name as a string. But you can use the stringer tool from the standard toolkit to do this for you:

For example, given this snippet,

 package painkiller type Pill int const ( Placebo Pill = iota Aspirin Ibuprofen Paracetamol Acetaminophen = Paracetamol ) 

execution of this command

 stringer -type=Pill 

the pill_string.go file will be created in the same directory, in the painkiller package containing the definition

 func (Pill) String() string 

It is recommended that you use the go generate command for Go 1.4 +.

+16
source share

All Articles