简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM