duanping5306 2016-08-26 09:31
浏览 116
已采纳

枚举作为go中变量的属性

Let's say I have something like this:

const (
    FOO int = iota
    BAR
    BAZ
)

And I can access to variables by FOO, BAR and so on. But storing a big amount of constants in one namespace isn't good so I'm trying to hide this enum in structure or something like that so I can get value by typing actions.FOO in same namespace. I've tried many ways but didn't find anything like that. I would like to mention that easiest workaround, in this case, will be anonymous structure but I wanna keep auto indexing with iota.

  • 写回答

1条回答 默认 最新

  • doujiao7483 2016-08-26 22:44
    关注

    The only way to assign some sort of enumerable behind the property without creating the separate package that I found is to use anonymous structure.

    type someType int
    
    var ConstantsList = struct {
       FOO, BAR, BAZ someType
    }{1, 2, 3}
    

    There are few downsides of using it, it's not immutable, and doesn't have auto increment.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部