iota 的确切含义是什么?

What's the exact meaning of iota?

在下面的代码中:

const (
    signature uint32 = 0xae3179fb
    dhkxGroup = 2

    ReplySuccessful byte = iota
    ReplyBufferCorrupted
    ReplyDecryptFailed
    ReplySessionExpired
    ReplyPending
)

ReplySuccessful 被编译为 2,而我认为它应该是 ZERO。如果我将 signaturedhkxGroup 移动到 ReplyPending 下面,那么 ReplySuccessful 就会变成 0。

这是为什么?

PS。对我来说,使用 iota 的唯一“好处”是你可以省略分配给后面常量的值,这样你就可以轻松 modify/insert 新值。但是,如果 iota 不是 FIXED 为零,它可能会导致大问题,尤其是在执行诸如通信协议之类的事情时。

spec 定义了 iota 在 Go 中的用法(强调已添加):

Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero.

注意索引是相对于ConstSpec的,基本上是指当前const块。

特别感兴趣的可能是提供的示例:

const (
  a = 1 << iota  // a == 1  (iota == 0)
  b = 1 << iota  // b == 2  (iota == 1)
  c = 3          // c == 3  (iota == 2, unused)
  d = 1 << iota  // d == 8  (iota == 3)
)

注意第 3 行(iota 值 2)未使用。您基本上是一样的,首先是两个未使用的值。

您在代码中的意思可能是:

const (
    signature uint32 = 0xae3179fb
    dhkxGroup = 2
)

const (
    ReplySuccessful byte = iota
    ReplyBufferCorrupted
    ReplyDecryptFailed
    ReplySessionExpired
    ReplyPending
)

看到了on the playground