Menu Close

iota enums in Go

Unlike many other programming languages, Go has no build-in enum type. This article shows how to build enum like logic in Go using the iota keyword.

iota keyword

The iota keyword is the representation of an integer, which gets increment by one every time it gets used in the source code. It resets to 0 whenever “const” appears in the source code:

const (
	i = iota // 0
	j = iota // 1
	k = iota // 2
)

const (
	l = iota // 0
)

You can use the shorthand syntax for consecutive iota values:

const (
	i = iota // 0
	j        // 1
	k        // 2
)

There’s a great post on different usage types of iota by Inanc Gumus, but for this post, we’ll focus on the enum use case.

Full enum example with iota

Now that we know the basics of the iota keyword, let’s look into a full enum example. In this example we’re defining an enum equivalent for log levels:

const (
	Trace   = iota // 0
	Debug          // 1
	Info           // 2
	Warning        // 3
	Error          // 4
)

Note: The Go naming conventions for constants is UpperCammelCase

In some cases, you might need a string representation of your enum values. To do this, we can define a custom int type and provide a string function for it:

type LogLevel int

const (
	Trace   LogLevel = iota // 0
	Debug                   // 1
	Info                    // 2
	Warning                 // 3
	Error                   // 4
)

var LogLevelStrings = []string{"[Trace]", "[Debug]", "[Info]", "[Warning]", "[Error]"}

func (l LogLevel) String() string {
	return LogLevelStrings[l]
}

Here is an example of this enum in practice:

package main

import "fmt"

type LogLevel int

const (
	Trace   LogLevel = iota // 0
	Debug                   // 1
	Info                    // 2
	Warning                 // 3
	Error                   // 4
)

var LogLevelStrings = []string{"[Trace]", "[Debug]", "[Info]", "[Warning]", "[Error]"}

func (l LogLevel) String() string {
	return LogLevelStrings[l]
}

func Log(l LogLevel, message string) {
	fmt.Printf("%s: %s\n", l, message)
}

func main() {
	Log(Trace, "Somethin tracworthy occured.")     // [Trace]: Something tracworthy occured.
	Log(Debug, "This should help you to debug.")   // [Debug]: This should help you to debug.
	Log(Info, "This programm is running.")         // [Info]: This programm is running.
	Log(Warning, "Something suspicious happened.") // [Warning]: Something suspicious happened.
	Log(Error, "An error occured")                 // [Error]: An error occured
}

I hope this post will help you with implementing your own enum logic in Go.

1 Comment

Comments are closed.