英文:
What's the exact meaning of iota?
问题
在下面的代码中:
const (
signature uint32 = 0xae3179fb
dhkxGroup = 2
ReplySuccessful byte = iota
ReplyBufferCorrupted
ReplyDecryptFailed
ReplySessionExpired
ReplyPending
)
ReplySuccessful
被编译为 2
,但我认为它应该是零。如果我将 signature
和 dhkxGroup
移到 ReplyPending
下面,那么 ReplySuccessful
就变成了 0。
为什么会这样?
PS. 对我来说,使用 iota
的唯一“好处”是你可以省略后续常量的赋值,这样你可以轻松修改/插入新的值。然而,如果 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.
答案1
得分: 6
spec定义了Go语言中iota的用法(重点添加):
在常量声明中,预声明的标识符iota表示连续的无类型整数常量。它的值是该常量声明中相应ConstSpec的索引,从零开始。
请注意,索引是相对于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
)
在playground上查看它。
英文:
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:
> golang
> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论