If you’ve ever spoken with me about programming, it’s very likely that my affinity for the Go programming language has come up. Go1 is a powerful and yet, incredibly simple language for doing everything from web servers to systems programming.

The team behind Go is incredibly careful and selective when it comes to adding new features to the language, and because of this we quickly find that the language doesn’t offer a syntax for Enumerations (or enums).

#What’s an Enum(eration)?

For those that don’t know, an enumeration is a distinct type that consists of a set of named constants called the enumerator list. It’s essentially a good way to produce a set of human readable values.

Let’s create a simple example of enums in action using C#. We’re going to have an enum that contains the seasons of a year and a DescribeSeason function that relies on a specific season to be given.

using System;

enum Season {
  Winter, // 0
  Spring, // 1
  Summer, // 2
  Fall,   // 3
}

class MainClass {

  public static void Main (string[] args) {
    Console.WriteLine(DescribeSeason(Season.Summer));
  }
  
  private static string DescribeSeason(Season season) {
    switch (season) {
      case Season.Winter:
        return "Brrrr... It's cold!";
      case Season.Spring:
        return "Oh pretty flowers!  AHHH a bee!";
      case Season.Summer:
        return "Time to hit the beach!";
      case Season.Fall:
        return "The leaves! They're dying!";
      default:
        return "How did you get here?";
    }
  }
}

#No Native Enums?

At first this seemed like an odd choice to me that the Go team wouldn’t include such a useful feature for a typed language. However, upon digging a bit deeper, I quickly discovered why there is no enum keyword:

You can define new types based on existing types.

In Go, you can create a new, distinct type from an existing one using the syntax:

type NewType ExistingType
Definitions vs aliases

This is a type definition, not an alias. NewType shares the same underlying representation as ExistingType, but it’s treated as its own type, so you can’t accidentally pass an ExistingType variable where a NewType is expected. Go does also have actual type aliases (type NewType = ExistingType), but those are just another name for the exact same type, which isn’t what we want here.

If we think about what the most common enum is under the hood, an integer, we can easily define our enumeration type. Let’s try and replicate our C# example from above, but in Go.

package main

import "fmt"

type Season int

const (
	SeasonWinter Season = 0
	SeasonSpring Season = 1
	SeasonSummer Season = 2
	SeasonFall   Season = 3
)

func main() {
	fmt.Println(DescribeSeason(SeasonSummer))
}

func DescribeSeason(season Season) string {
	switch season {
	case SeasonWinter:
		return "Brrrr... It's cold!"
	case SeasonSpring:
		return "Oh pretty flowers!  AHHH a bee!"
	case SeasonSummer:
		return "Time to hit the beach!"
	case SeasonFall:
		return "The leaves! They're dying!"
	default:
		return "How did you get here?"
	}
}

You’ll likely notice that our enum isn’t a dedicated language construct like in C#, C++, Java, etc… But, by using a distinct type with named constants we are able to achieve the same result.

#Adding iota

Let’s remove the need of manual value assignment to our custom Season enumeration type. We can do this using iota, which is a quirky2, universal counter that is provided natively by Go.

Though the syntax is a bit funky for a couple of reasons, maintaining the enumeration down the road becomes less of a hassle as we don’t need to manually reassign or reorder values.

const (
	SeasonWinter Season = iota
	SeasonSpring
	SeasonSummer
	SeasonFall
)

#It’s Not Airtight

Unlike a “real” enum, Go will happily let you pass in a plain number as long as it’s a constant. Untyped constants get converted to Season automatically, so this compiles just fine:

DescribeSeason(7) // returns "How did you get here?"

You do still get some protection though. Variables of a different type won’t be converted for you:

n := 7
DescribeSeason(n) // compile error: cannot use n (variable of type int) as Season value

So the Season type does help, but it isn’t a guarantee. This is why that default case in our switch is worth keeping around.

#Make the Zero Value Mean Something

Every type in Go has a zero value, and for Season that’s 0… which happens to be SeasonWinter. That means any Season you forget to set, like a field in a struct, is quietly winter.

A common way to avoid this is to reserve 0 for an “unknown” value:

const (
	SeasonUnknown Season = iota
	SeasonWinter
	SeasonSpring
	SeasonSummer
	SeasonFall
)

Now if a SeasonUnknown shows up somewhere, you know something was never set rather than silently getting the wrong season.

#Printing Names with stringer

If you try printing one of our seasons with fmt.Println(SeasonSummer), you’ll just get a number. Rather than writing a String() method by hand, Go has a tool called stringer that will generate one for you.

go install golang.org/x/tools/cmd/stringer@latest

Then add a go:generate comment above your type and run go generate:

//go:generate stringer -type=Season -trimprefix=Season
type Season int

This generates a season_string.go file with a String() method, so fmt.Println(SeasonSummer) now prints Summer. And since it’s generated, you just re-run go generate whenever you add a new season.