What's the exact meaning of iota?
Asked Answered
W

1

6

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.

Wendell answered 12/7, 2021 at 10:10 Comment(0)
H
9

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

Hesperus answered 12/7, 2021 at 10:16 Comment(2)
Thanks. The definition of iota is now clear to me, however, I still don't know why it is designed like this. I'll open a new question.Wendell
In general, I suggest not to use iota at all. Since it generates auto increment values, if tomorrow we reorder our constants, they would have a different value & this would result in inconsistent application / db state. Hence, I suggest to always provide hard coded integral value for each of the constant.Foal

© 2022 - 2024 — McMap. All rights reserved.