iota的确切含义是什么?

huangapple go评论82阅读模式
英文:

What's the exact meaning of iota?

问题

在下面的代码中:

const (
	signature uint32 = 0xae3179fb
	dhkxGroup = 2

	ReplySuccessful byte = iota
	ReplyBufferCorrupted
	ReplyDecryptFailed
	ReplySessionExpired
	ReplyPending
)

ReplySuccessful 被编译为 2,但我认为它应该是。如果我将 signaturedhkxGroup 移到 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
&gt; const (
&gt; a = 1 &lt;&lt; iota // a == 1 (iota == 0)
&gt; b = 1 &lt;&lt; iota // b == 2 (iota == 1)
&gt; c = 3 // c == 3 (iota == 2, unused)
&gt; d = 1 &lt;&lt; iota // d == 8 (iota == 3)
&gt; )
&gt;

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

huangapple
  • 本文由 发表于 2021年7月12日 18:10:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/68345567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定