Go: How to use enum as a type?

Issue

I have a list of events (enum) which defines the particular event:

package events

const (
    NEW_USER       = "NEW_USER"
    DIRECT_MESSAGE = "DIRECT_MESSAGE"
    DISCONNECT     = "DISCONNECT"
)

And there is a struct that will use this enum as one of its attribute

type ConnectionPayload struct {
    EventName    string      `json:"eventName"`
    EventPayload interface{} `json:"eventPayload"`
}

Is there a way I can use enum as a type for EventName instead of string?

This is possible in typescript not sure how to do it in golang.

I want the developers to forcefully use correct event name using the enum instead of making a mistake by using any random string for eventname.

Solution

You can do it by generating code like the below.


type EventNames string

const (
    NEW_USER       EventNames = "NEW_USER"
    DIRECT_MESSAGE EventNames = "DIRECT_MESSAGE"
    DISCONNECT     EventNames = "DISCONNECT"
)

then change your struct to this:

type ConnectionPayload struct {
    EventName    EventNames  `json:"eventName"`
    EventPayload interface{} `json:"eventPayload"`
}

Answered By – ttrasn

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.