How to declare enums in golang?


(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #1

How to declare Enum in golang like Java:

enum WeekDay {
SATURDAY,
SUNDAY,
... 
}

I found a solution:

type WeekDay int
const (
	Saturday WeekDay = 1
	Sunday WeekDay = 2
)

func aFunc(WeekDay WeekDay)  {
...
}

But the problem is that I can use an explicit integer instead of Weekday when want do declare arguments:

aFunc(55)

How to restrict passing Integer in parameter?

Thanks in advance.


(Norbert Melzer) #2

You can’t.

Also the more idiomatic way were to use iota:

type WeekDay int

const (
  Saturday WeekDay = iota
  Sunday
  Monday
  Tuesday
  // ...
}

(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #3

The iota can’t restrict bad usage.
Thanks for response.


(Norbert Melzer) #4

I never said that. I said “You can’t” and showed the use of iota as a more idiomatic approach, nothing more, nothing less.


(Ήαϻe̸d̨ MΌsϮαϝαe̸ΐ༄) #5

My apologies i’m only angry because of Golang’s limitations


(Johan Dahl) #6

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…