【问题标题】:How can I write an enum with "intellisence support"?如何编写具有“智能感知支持”的枚举?
【发布时间】:2021-12-03 13:19:45
【问题描述】:

在 go 中你可以这样写一个枚举

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)
    }
}

现在你写一个枚举,它不仅有 4 个选项,而是 100 个。我想要的是一个给我“Inellisence 支持”的枚举:如果我输入枚举,输入一个 .,我想知道哪些选项有没有枚举。

这可能是这样的一个例子。有没有更好的办法?


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()
    ...
}

【问题讨论】:

  • 使用公共前缀开始枚举值,例如DirNorthDirSouth。现在,当您输入 packagename.Dir 时,您将获得可能值的列表。
  • 我明白你的意思,但这似乎是一种解决方法
  • 除了你的问题,无论如何,这是一个很好的命名策略,标准库也使用。请参阅net/http 包:MethodGetMethodPost ... 和 StatusOKStatusCreated... 我不认为这是一种解决方法,我认为这是“用一块石头杀死两只鸟”。
  • 好的。 LGTM。将此作为答案发布,我将关闭此问题。

标签: go enums


【解决方案1】:

我建议枚举值的名称以公共前缀开头,例如Dir 像这样:

const (
    DirNorth Direction = iota
    DirSouth
    DirEast
    DirWest
)

这样做,当您输入packagename.Dir 时,您将获得可能值的列表。

因此,除了应用良好的命名策略之外,您还将同时获得改进的自动完成功能,并且您的源代码变得更具可读性(尤其是如果有很多枚举值并且其中有更多常用词) .

这也被标准库使用,很好的例子在 net/http 包中:

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
    // ...
)

查看相关问题:Glued acronyms and golang naming convention

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    相关资源
    最近更新 更多