2

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()
    ...
}
User12547645
  • 6,955
  • 3
  • 38
  • 69
  • 2
    Start the enum values with a common prefix, e.g. `DirNorth`, `DirSouth`. Now when you type `packagename.Dir`, you'll get the list of possible values. – icza Dec 03 '21 at 13:22
  • I get what you mean, but that seems like a workaround – User12547645 Dec 03 '21 at 13:26
  • 3
    Aside from your issue, this is a good naming strategy anyway, used by the standard library too. See the `net/http` package: `MethodGet`, `MethodPost` ..., and `StatusOK`, `StatusCreated`... I don't consider this a workaround, I consider this "kill two birds with one stone". – icza Dec 03 '21 at 13:38
  • 1
    Alright. LGTM. Post this as an answer and I'll close this issue. – User12547645 Dec 03 '21 at 13:42

1 Answers1

1

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

icza
  • 389,944
  • 63
  • 907
  • 827