Can constants be grouped in Go like Java's Enum?

From what I’ve seen, Go treats consts as non-modifiable variables which have a type. But I wonder if groups of related constants can be grouped like Java does with enums? For example, suppose I wanted MONTH_TYPE (months of the year) and WEEKDAY_TYPE (Sunday, Monday, etc). Does Go permit this?

There was a lot of discussion about this :
But using type in const seems to raise more problems than it solves.

I feel like this is different. That discussion wants to extend const to apply to non-basic types. Enums in Java basically are constants, but that have a type for the group of constants. It’s similar to what Go already does when you define your own type to be Foo (which is really a string or a struct) but would apply to a group of constants (which could still be, say, initialized to strings). For now, it looks like the answer is no. Go does not support that a group of constants has its own type (I guess that would be equivalent to the constants having a type of Foo which is defined as String, which presumably is not permitted?

type Foo string
const x Foo = "x"  // Is this allowed?

Why has noone told about this pattern?

type Foo int

const (
  VariantA Foo = iota

Ps: from mobile therefore may include auto"corrections".

1 Like

Yes, that’s allowed, and it behaves the way people would expect it to behave:

type Weekday string

const (
	Monday    Weekday = "Monday"
	Tuesday           = "Tuesday"
	Wednesday         = "Wednesday"
	Thursday          = "Thursday"
	Friday            = "Friday"

See here for an example. That doesn’t compile because Monday is a constant and you cannot assign a new value to it.

What you don’t have is constants with non-basic types. Since that includes arrays and slices of basic types, the above example might look a little strange, since strings are convertible to rune slices.

Even though I’ve already seen this in code, I’m not a friend of it, as comparing strings takes longer than comparing integers.

So your preference would be to define this as an int, and perhaps, for printing purposes, create a function with a caller of Weekday, which prints, perhaps based on a slice (or array). OK, I can see that.

I’d implement fmt.Stringer and fmt.GoStringer for them. Thats so much nicer than having a string slipping through which will later on break your code after fixing a typo in the constants value!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.