dousigan0499 2013-01-20 16:07
浏览 51
已采纳

在Go中表示枚举的惯用方式是什么?

I'm trying to represent a simplified chromosome, which consists of N bases, each of which can only be one of {A, C, T, G}.

I'd like to formalize the constraints with an enum, but I'm wondering what the most idiomatic way of emulating an enum is in Go.

  • 写回答

7条回答 默认 最新

  • doubi9531 2013-01-20 16:15
    关注

    Quoting from the language specs:Iota

    Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. It is reset to 0 whenever the reserved word const appears in the source and increments after each ConstSpec. It can be used to construct a set of related constants:

    const (  // iota is reset to 0
            c0 = iota  // c0 == 0
            c1 = iota  // c1 == 1
            c2 = iota  // c2 == 2
    )
    
    const (
            a = 1 << iota  // a == 1 (iota has been reset)
            b = 1 << iota  // b == 2
            c = 1 << iota  // c == 4
    )
    
    const (
            u         = iota * 42  // u == 0     (untyped integer constant)
            v float64 = iota * 42  // v == 42.0  (float64 constant)
            w         = iota * 42  // w == 84    (untyped integer constant)
    )
    
    const x = iota  // x == 0 (iota has been reset)
    const y = iota  // y == 0 (iota has been reset)
    

    Within an ExpressionList, the value of each iota is the same because it is only incremented after each ConstSpec:

    const (
            bit0, mask0 = 1 << iota, 1<<iota - 1  // bit0 == 1, mask0 == 0
            bit1, mask1                           // bit1 == 2, mask1 == 1
            _, _                                  // skips iota == 2
            bit3, mask3                           // bit3 == 8, mask3 == 7
    )
    

    This last example exploits the implicit repetition of the last non-empty expression list.


    So your code might be like

    const (
            A = iota
            C
            T
            G
    )
    

    or

    type Base int
    
    const (
            A Base = iota
            C
            T
            G
    )
    

    if you want bases to be a separate type from int.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题