https://stackoverflow.com/questions/14426366/what-is-an-idiomatic-way-of-representing-enums-in-go

问题

我正尝试表示一个简单的染色体,它由 N 个碱基组成,它们只能是 {A, C, T, G} 中的一个。

我想用枚举类型将它们约束,但我想知道 Go 中通常如何模拟一个枚举类型。

回答

引用语言规范: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:

译:在常量声明中,预先声明的标识符 iota 表示连续的无符号整型变量。它在每个 ConstSpec 上递增,而在新的 const 关键字出现时重置为 0。它可以用作声明一组相关的常量。

const (  // iota 已重置为 0
        c0 = iota  // c0 == 0
        c1 = iota  // c1 == 1
        c2 = iota  // c2 == 2
)

const (
        a = 1 << iota  // a == 1 (iota 已重置为 0)
        b = 1 << iota  // b == 2
        c = 1 << iota  // c == 4
)

const (
        u         = iota * 42  // u == 0     (无符号整型常量)
        v float64 = iota * 42  // v == 42.0  (float64 常量)
        w         = iota * 42  // w == 84    (无符号整型常量)
)

const x = iota  // x == 0 (iota 已重置为 0)
const y = iota  // y == 0 (iota 已重置为 0)

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

译:在表达式列表中每个 iota 的值相等,因为它只在 ConstSpec 上递增:

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

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

译:最后一个例子利用了列表中最后一个非空表达式会隐式重复的特性(注:若省略赋值表达式则重复上面最后一个非空表达式)。


所以你的代码应该是:

const (
        A = iota
        C
        T
        G
)

或者

type Base int

const (
        A Base = iota
        C
        T
        G
)

如果你希望 Base 作为类型来与 int 区分的话。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注