CyberSpy

Rantings from a guy with way too much free time

Go Get Interfaced: Enums in Golang

Golang, Interfaces, and Enums

So here’s a nice golang idiom that I ran across years ago that I found generally useful. Golang, unlike languages like c doesn’t natively support enumerations. Instead, constants typically are used when creating a list of enumerations. But, go is a strongly-typed language, so we can do better than simply using constants - we can type our enumeration with the use of a type declaration.

type DogState uint

By defining a type for our enumeration, we can consistently pass and return typed-values among our functions operating on our enumeration. Okay, that’s all well and good, but what happens when we want to go between uint values and string representations of those values; a commonly used paradigm when working with enumerations. One approach would have us write mapping functions that might switch among the values to return a string. Or, when going from a string name of an enumeration to the uint value, we might use a map[string]. That’s a doable implementation, but there’s an easier, and more idiomatic way.

Continue reading