Enum with String function

yourbasic.org/golang

Basic solution

A group of constants enumerated with iota might do the job.

const (
    Sunday    int = iota // Sunday == 0
    Monday               // Monday == 1
    Tuesday              // Tuesday == 2
    Wednesday            // …
    Thursday
    Friday
    Saturday
)

In the example, we also rely on the fact that expressions are implicitly repeated in a paren­thesized const declaration – this indicates a repetition of the preceding expression and its type.

Add a string representation

You could also introduce a new type…

type Suite int

const (
    Spades Suite = iota
    Hearts
    Diamonds
    Clubs
)

…and give it a String function:

func (s Suite) String() string {
	return [...]string{"Spades", "Hearts", "Diamonds", "Clubs"}[s]
}

Here is the new type in action.

var s Suite = Hearts
fmt.Print(s)
switch s {
case Spades:
	fmt.Println(" are best.")
case Hearts:
	fmt.Println(" are second best.")
default:
	fmt.Println(" aren't very good.")
}
Hearts are second best.

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share this page: