Marcel Schramm

Go lacks enums

Written on 20 September 2020 by Marcel Schramm

As a Java programmer, I heavily make use of enums. The reason is quite simple. Whenever I have a fixed set of values, i can easily iterate over them and switch over them. The reason why I really like switching over enums though, is that I am using an IDE that notifies me of every switch that doesn't handle all possible values of an enum. Let's say I had the following Java code:

public enum CarManufacturers {

void someFunction(CarManufacturer manufacturer) {
  switch (manufacturer) {
    case FIAT:

I would get an error stating that a switchcase I had wasn't handling all possible values and doesn't have a default case either. For those who don't know, the default case is basically a catch-all case for that can be used as a last resort. While switch-cases over enums are technically not exhaustive in Java, probably because of being able to technically extend an enum via reflection, the IDE still treats it that way. If you extend an enum at runtime you deserve to burn either way.

So, the value that this provides to me, is that I can extend an enum and be notified of all code pieces that need work.

Now let's look at Golang. In Go we don't have enums. The idiomatic go way for such things appear to be type aliases and the iota keyword.

For example:

type CarManufacturer int

const (
    Fiat = iota

var Gotcha CarManufacturer = 5

func someFunction(x CarManufacturer) {
    switch x {
    case Fiat:
    case Ford:
    case Mercedes:
    case Opel:

This creates the constants Fiat to Opel, incrementing their value by one starting from 0. However, as you can see, I can manually create another value with the same type. The problem is, that anyone can basically do this. So you never know whether you get some weird and unexpected values at runtime. While you can still handle those with a default case, my problem here really is the lack of static analysis and warnings. As the compiler basically can't know whether you've handled all cases.