Can somebody explain this for loop definition to me I found in Hashicorp's immutable radix tree package?

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

Can somebody explain this for loop definition to me I found in Hashicorp's immutable radix tree package?

问题

所以,我已经写了几年的Go语言了,虽然我知道for循环不仅仅适用于日常情况,但是对于这个例子,我还是不太明白其中的含义。

我的意思是,我可以使用它,但是我不理解它。

for key, _, ok := it.Next(); ok; key, _, ok = it.Next()

这段代码来自于这里的不可变基数树包:https://github.com/hashicorp/go-immutable-radix。

实际上,我提问是因为为了检索我放入树中的数据,我稍微修改了代码(将 _ 修改为 blob),但是现在我不确定是否应该在第二部分中做同样的修改。

for key, blob, ok := it.Next(); ok; key, _, ok = it.Next()
英文:

So, I've been writing Go for some years now, and while I know there is more to the for loop than the "usual" day-to-day case, this, I just don't quite get what is going on.

I mean, I can use it, but I don't get it.

for key, _, ok := it.Next(); ok; key, _, ok = it.Next()

It is from the immutable radix tree package here: https://github.com/hashicorp/go-immutable-radix.

I actually ask, because to retrieve the data I put in the tree, I have altered the code slightly () _ to blob), but now I am not sure if I should do the same in the second part.

for key, blob, ok := it.Next(); ok; key, _, ok = it.Next()

答案1

得分: 1

循环从调用it.Next()开始,并在ok为true时继续执行。每次循环结束时,ok会通过it.Next()被重置。在每次迭代中,循环还会设置key

你的修改在初始化时设置了blob,但它再也没有设置过blob。对于所有的迭代,blob将保持从it.Next()获取的第一个值。很可能你还应该在循环的最后一个条件中设置blob,这样你就可以获取下一个元素的blob

英文:

The loop starts with calling it.Next(), and continues as long as ok is true. ok is reset with it.Next() at the end of every loop. At each iteration, the loop also sets key.

Your modification sets blob at the initialization, but it never sets blob again. For all iterations, blob will have the first value it got from it.Next(). It is likely that you should set blob at the last condition of the loop as well, so you can get the blob for the next element.

huangapple
  • 本文由 发表于 2021年11月1日 06:59:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/69791214.html
匿名

发表评论

匿名网友

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

确定