goiota

What's the exact meaning of iota?


In the code below:

const (
    signature uint32 = 0xae3179fb
    dhkxGroup = 2

    ReplySuccessful byte = iota
    ReplyBufferCorrupted
    ReplyDecryptFailed
    ReplySessionExpired
    ReplyPending
)

ReplySuccessful is compiled to 2, while I think it should definitly be ZERO. If I move signature and dhkxGroup below ReplyPending, then ReplySuccessful becomes 0.

Why is this?

PS. To me, the only "benefit" of using iota is that you can ommit the value assigned to later constants, so that you can easily modify/insert new values. However, if iota is not FIXED to zero, it could cause big problem especially in doing things like communication protocols.


Solution

  • The spec defines iota's usage in Go (emphasis added):

    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.

    Note that the index is relative to the ConstSpec, basically meanining the current const block.

    Of particular interest is probably the example provided:

    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)
    )
    

    Notice line 3 (iota value 2) is unused. You have essentially the same, with two unused values coming first.

    What you probably meant in your code is:

    const (
        signature uint32 = 0xae3179fb
        dhkxGroup = 2
    )
    
    const (
        ReplySuccessful byte = iota
        ReplyBufferCorrupted
        ReplyDecryptFailed
        ReplySessionExpired
        ReplyPending
    )
    

    See it on the playground