Enums with Golang

Jul 30, 2019 | Reading time: 2 minutes

Enumerations or enums are a group of similar constants with similar behavior or data. In golang we create enums by declaring them as constants and grouping them by a type.

Basic enum

First we declare the new type that groups our Enums.

type LogLevel int

Next we declare our constants and give them the new type.

const (
  ERROR   LogLevel = 1
  INFO    LogLevel = 2
  TRACE   LogLevel = 3
  WARN    LogLevel = 4
)

Iota

The iota identifier is used in const declarations to simplify definitions of incrementing numbers.

type LogLevel int

const (
  ERROR  LogLevel = iota // 0
  INFO   LogLevel        // 1
  TRACE  LogLevel        // 2
  WARN   LogLevel        // 3
)

The values of iota are zero-based and capable of being used in expresions.

const (
  Error LogLevel = 1 + iota // 1
)

We can take advantage of iota being zero-based and golang’s default zero values to improve error handling.

type LogLevel int

const (
  UNSPECIFIED LogLevel = iota // 0
  ERROR       LogLevel        // 1
  INFO        LogLevel        // 2
  TRACE       LogLevel        // 3
  WARN        LogLevel        // 4
)

Example usage

A common example where you might see Enum usage is a case statement.

func setLogLevel(level LogLevel) {
  switch level {
    case UNSPECIFIED:
      // Do something
      fmt.Println("Log level was not set")
      return

    case ERROR:
      // Do something
      fmt.Println("Log level set to ERROR")
      return

    case INFO:
      // Do something
      fmt.Println("Log level set to INFO")
      return

    case TRACE:
      // Do something
      fmt.Println("Log level set to TRACE")
      return

    case WARN:
      // Do something
      fmt.Println("Log level set to WARN")
      return

    default:
      // Handle all other edge cases or errors
      return
  }
}

Adding functionality

Adding String() function to return the enum as a string.

var logLevelStrings = []string {
  "UNKNOWN",
  "ERROR",
  "INFO",
  "TRACE",
  "WARN",
}

func (level LogLevel) String() string {
  return logLevelStrings[level]
}

Adding Ordinal() function to return the int value of the enum.

func (level LogLevel) String() []string {
  return int(level)
}

comments powered by Disqus