Golang enum Tutorial

Sometime you might be need to implement enumeration in your go code. An enum type is a special data type that allows variables to be defined as sets of predefined constants. If you come from java world you would probably write enum like this.

public enum Color {
    RED,
    GREEN, 
    PROBLEM; 
}

How to use enum in Go?

So the idiomatic way to do enum in Go is like this.

package enum

const (
	RED = iota
	GREEN
	BLUE
)

By default the value will be assign as untyped int and it will created from 0. So the constant value will be RED=0, GREEN=1, BLUE=2.

What if you need the value start from one? Yeah, we can do that there's several way we can accomplish that. You can pick which one do you like

Simply add +1

Just add iota + 1 to the first assign value.

const (
	RED = iota + 1
	GREEN
	BLUE
)

The constant value will be RED=1, GREEN=2, BLUE=3.

Assign to empty variable

The other way is just assign iota to unused variable _.

const (
	_ = iota
	RED
	GREEN
	BLUE
)

The constant value will be RED=1, GREEN=2, BLUE=3.

Custom value

If you need custom value for the constant you just can simply override the value this way.

const (
	_ = iota
	RED
	GREEN
	BLUE = 100
)

The constant value will be RED=1, GREEN=2, BLUE=100.

Print the enum to string

Here's one case if you need to print the enum to string.

type Color int

const (
	RED Color = iota
	GREEN
	BLUE
)

func (c Color) String() string {
	return []string{"RED", "GREEN", "BLUE"}[c]
}

func RunEnum() {
	fmt.Println(RED) // print: RED
}

How to use it?

So here's example on how we can use this enum to print colored text in the console.

package enum

import (
	"fmt"
)

const escape = "\x1b"

const (
	NONE = iota
	RED
	GREEN
	YELLOW
	BLUE
	PURPLE
)

func format(color int) string {
	if color == NONE {
		return fmt.Sprintf("%s[%dm", escape, color)
	}

	return fmt.Sprintf("%s[3%dm", escape, color)
}

func RunEnum() {
	fmt.Printf("%s%s\n", format(RED), "I'm red")
	fmt.Printf("%s%s\n", format(GREEN), "I'm green")
	fmt.Printf("%s%s\n", format(YELLOW), "I'm yellow")
	fmt.Printf("%s%s\n", format(BLUE), "I'm blue")
	fmt.Printf("%s%s\n", format(PURPLE), "I'm purple")
	fmt.Printf("%s%s\n", format(NONE), "I'm white")
}

This will print colored text like this.

I'm red
I'm green
I'm yellow
I'm blue
I'm purple
I'm white

Bonus

If you having an issue to run the colored text in windows add this hack to enable color formating in windows.

import (
	"fmt"
	"os"

	"golang.org/x/sys/windows"
)

func init() {
	stdout := windows.Handle(os.Stdout.Fd())
	var originalMode uint32

	windows.GetConsoleMode(stdout, &originalMode)
	windows.SetConsoleMode(stdout, originalMode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING)
}