How to declare enums in golang?

One (stupid) way to do it is to create a new type and implement a method on it which is according to some interface

package weekday

// Create a new type weekday
type weekday string

// Implement some method on it
// which returns the not exported type
func (w weekday) isWeekday() weekday {
	return w
}

// The interface which is exported
type Weekday interface {
	isWeekday() weekday
}

const (
	Monday   = weekday("Monday")
	Tuesday  = weekday("Tuesday")
	Wendsday = weekday("Wendsday")
	Thursday = weekday("Thursday")
	Friday   = weekday("Friday")
	Saturday = weekday("Saturday")
	Sunday   = weekday("Sunday")
)

When you can use this type/interface and you must really work it to assign some random value to it

package main

import (
	"fmt"

	"./weekday"
)

// Use the interface for parameters
func print(w weekday.Weekday) {
	fmt.Println("Day is", w)
}

func main() {
	var d1 = weekday.Monday
	var d2 = weekday.Tuesday

	fmt.Println(d1, d2, d1 == d2, d1 == weekday.Monday)

	print(d1)
}

Output

$ go run main.go
Monday Tuesday false true
Day is Monday

But this is rather clumsy and ugly…

1 Like