Skip to main content

Command Palette

Search for a command to run...

Creating Enums type in GO

Updated
2 min read
Creating Enums type in GO
P

Actively looking for opportunites in DevOps | Fullstack Engineer . I write APIs using Go and React components for the UI.

Connect with me on twitter : https://twitter.com/prakhartwt

Check my work at github : https://github.com/prakharporwal

Ahh ! Why does Go Not support Enums . Well There is a workaround you can use to make Enum like setup in Go.

Well Go lang support only string and int as const

One of the ways is to do it this way.

Create a Type for you Enum and what all you want with it. example Errors. eg. can have a Message, and a Status Code

type APIError struct {
    ErrorCode string `json:"error-code"`
    Message   string `json:"message"`
}

Now you can add up you variables using the var keyword and declaring the name and value of the constants.

var (
    InvalidPayload = APIError{
        ErrorCode: errorType + "01",
        Message:   "Invalid Payload. Check the JSON body.",
    }
)

But, I know its mutable, but you want it to be constant.

so we can use something called iota in go

type EnumType int
const (
    Error1 EnumType = iota 
    Error2
    Error3
)

iota auto increments the const values and can be use for int constant only, so Error1 will have value 0 Error2 will be 1 and so on .......... And Along with this we can have a map to get the actual Error using these const as key.

func(e EnumType) GetErr() *APIError{
     return mapOfErr[e]
}

var mapOfErr = map[EnumType]*APIError{
    Error1: {
        StatusCode:  "500",
        Message:    "Oops!  something is broken and its not you, its me.",
    },
    Error2: {
        StatusCode:  "401",
        Message:    " Can't remember your password correctly, we will help!",
    }
}

Finally the file looks like this

package myErrors

type APIError struct {
    ErrorCode string `json:"error-code"`
    Message   string `json:"message"`
}

type EnumType int
const (
    Error1 EnumType = iota 
    Error2
    Error3
)

func(e EnumType) GetErr() *APIError{
        return mapOfErr[e]
}

var mapOfErr = map[EnumType]*APIError{
    Error1: {
        StatusCode:  "500",
        Message:    Oops!  something is broken and its not you, its me.",
    },
    Error2: {
        StatusCode:  "401",
        Message:    "Hey, you used to write 1000 words essay and can't remember your password correctly!",
    }
}

For using it somewhere you can use it using -

myErrors.Error1.GetErr()

where -myErrors is the package name -Error1 is the error const name and

  • GetErr() it the function which we defined.

Thank you for following till the end. I write about Go and React . Follow for more such hacky solutions