I was asked yesterday how you implement enums in Go. I didn’t know, so I spent some time this morning learning how to do it.
It turns out this is ridiculously easy to do and Go has the stringer tool which makes it super simple. (stringer codegens the code which prints your enum as a string.)
Example
I created a repo with the following structure:
go.mod
main.go
internal/coffee/coffee.go
internal/coffee/coffee_string.go
internal/coffee/coffee.go
looks like this:
package coffee
//go:generate stringer -linecomment -type=Coffee
type Coffee int
const (
Drip Coffee = iota // drip coffee
Latte // latte
Breve // breve
Cappuccino // cappuccino
)
Notice how I’m using //go:generate stringer -type=Coffee
to automatically generate internal/coffee/coffee_string.go
.
This allows the enums to print properly when I call them in main.go
like this:
package main
import (
"fmt"
"goenumtest/internal/coffee"
)
func PrintCoffee(c coffee.Coffee) {
fmt.Println("Coffee type is:", c)
}
func main() {
PrintCoffee(coffee.Drip)
PrintCoffee(coffee.Latte)
}
Running main.go
shows this:
$ go run main.go
Coffee type is: drip coffee
Coffee type is: latte
Super neat!
This is way better than how I am currently doing it.
GoByExample has a really good example of how this can work. And it links out to this helpful page as well.