go: Enumeration

There is no enumeration in Golang, but here is an example, which could be good start for any project, which needs to utilize enumeration. See https://play.golang.org/p/pD29UI37iq1

package main

import "fmt"

type EnumDay int

const (
	Monday EnumDay = iota
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
	Sunday
)

var EnumDays = [...]EnumDay{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}

type Day struct {
	N EnumDay
}

func (day EnumDay) String() string {
	dayName := []string{
		"Monday",
		"Tuesday",
		"Wednesday",
		"Thursday",
		"Friday",
		"Saturday",
		"Sunday"}
	if day < Monday || day > Sunday {
		return "Unknown day"
	}
	return dayName[day]
}
func (day Day) Next() Day {
	i := int(day.N)
	i++
	if i >= len(EnumDays) {
		i = 0
	}
	day.N = EnumDay(i)
	return day
}
func (day Day) Prev() Day {
	i := int(day.N)
	i--
	if i < 0 {
		i = len(EnumDays)-1
	}
	day.N = EnumDay(i)
	return day
}

func showDay(day Day) {
	fmt.Printf("Day is %s\n", day)
}

func main() {
	fmt.Print("EnumDays:  ")
	comma := ""
	for i, d := range EnumDays {
		fmt.Printf("%s%d:%s", comma, i, d)
		comma = ", "
	}
	fmt.Println()
	showDay(Day{Monday})
	showDay(Day{Saturday})
	showDay(Day{Sunday})

	day := Day{Monday}
	day = day.Prev()
	showDay(day)
	day = day.Next()
	showDay(day)
}
This entry was posted in golang, workday. Bookmark the permalink.

Leave a Reply