登录
首页 >  Golang >  Go问答

编写支持“智能”的枚举的方法是什么?

来源:stackoverflow

时间:2024-02-24 16:09:24 146浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《编写支持“智能”的枚举的方法是什么?》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

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

正确答案


我建议以公共前缀开始枚举值的名称,例如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

到这里,我们也就讲完了《编写支持“智能”的枚举的方法是什么?》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>