Enums and Golang


(Andre) #1

I’m curious about why Go does not support enums. Actually, I’ve never liked enums - I’ve got some of java background and never used it and very rarely met them in code. So in some sence I’m glag that there are other people thought that way and imlemented it in Go. What do you tnink about enums and what was the actual reason it’s not present in Go?


(Holloway) #2

Because Go has constant grouping? You can make multiple constant groups in a package.

Here is an example I use for mapping Linux error coding to Go’s error messages:

// Linux return codes
const (
        EPERM = iota + 1     // 1
        ENOENT               // 2
        ESRCH                // 3
        ...
)

// Error Messages for error objects
const (
       // ErrorNoPermission means the user did not give enough permission
       ErrorNoPermission = "no permission to run execution"

       // ErrorNoEntity means the user gave an invalid path
       ErrorNoEntity     = "no such file or directory"
       ...
)

// somewhere in my code
func translate(errorCode int) error {
        switch errorCode {
        case -EPERM:
               return fmt.Errorf(ErrorNoPermission)
        case -ENOENT:
               return fmt.Errorf(ErrorNoEntity)
        ...
        }
        return nil
}

Go compiler can smartly optimize constant to make your binary efficient so use as much as you can.

When to use enum & constants

Refrain from using magical values (e.g. magic numbers)

A vital practice in the industry is never use magic number. Hence, this is why enum exists at the first place. The practice is always make your code intuitively understandable without too much commenting. Consider the following examples:

func sample(...) int {
       ...
       return -1
}
func sample(...) int {
       ...
       return -EPERM
}

Both are returning integers. However, the latter is self-explainable so I don’t need to guess what -1 means or refers to dictionary/manual.

Reusing immutable values

Values that are immutable (e.g. list of error messages) is best to be grouped together for better organization.

This way, you need to alter the messages, you just need to alter the list of constants. This is very useful when you do i18n translations to the messages, where you just need to send 1 source codes containing the list instead of the entire repository.


Further reading materials:

  1. https://go101.org/article/constants-and-variables.html
  2. https://www.youtube.com/watch?v=pN_lm6QqHcw