How can I write an enum with "intellisence support"?

Viewed 51

In go you can write an enum like this

type Direction int

const (
    North Direction = iota
    South
    East
    West
)

func main() {

    // Declaring a variable myDirection with type Direction
    var myDirection Direction
    myDirection = West

    if (myDirection == West) {
      fmt.Println("myDirection is West:", myDirection)
    }
}

Now image you write an enum which not only has 4 option, but instead 100. What I want is an enum that gives me "Inellisence support": If I type the enum, type a ., I want to know what options are there for the enum.

An example how this could look like is this. Is there a better way?


type direction struct{}

func (d *direction) north() string {
    return "north"
}
func (d *direction) east() string {
    return "east"
}
func (d *direction) south() string {
    return "south"
}
func (d *direction) west() string {
    return "west"
}

func main() {
    var d direction
    d.east()
    ...
}
1 Answers

I suggest to start the names of the enum values with a common prefix, e.g. Dir like this:

const (
    DirNorth Direction = iota
    DirSouth
    DirEast
    DirWest
)

Doing so, when you type packagename.Dir, you'll get a list of the possible values.

So beside applying a good naming strategy, you'll get improved auto-completion at the same time, and your source code becomes more readable (especially if there are a lot of enum values and you have more common words among them).

This is also used by the standard library, great examples are in the net/http package:

const (
    MethodGet  = "GET"
    MethodHead = "HEAD"
    MethodPost = "POST"
    // ...
)

const (
    StatusContinue           = 100 // RFC 7231, 6.2.1
    StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
    StatusProcessing         = 102 // RFC 2518, 10.1

    StatusOK                 = 200 // RFC 7231, 6.3.1
    StatusCreated            = 201 // RFC 7231, 6.3.2
    // ...
)

See related question: Glued acronyms and golang naming convention

Related