drxpt06820 2019-02-04 08:41
浏览 653
已采纳

隐含索引时,Golang中“ for…range”的迭代顺序

https://golang.org/ref/spec#For_range

For statements with range clause

For an array, pointer to array, or slice value a, the index iteration values are produced in increasing order, starting at element index 0. If at most one iteration variable is present, the range loop produces iteration values from 0 up to len(a)-1 and does not index into the array or slice itself. For a nil slice, the number of iterations is 0.

According to the spec, iterating over a linear data structure (array or slice or string) in Go will get each of elements in there always in order the index increases.

for i, v := range []int{11, 22, 33, 44} {
    fmt.Println(i, v)
}

But the thing is that I can't really find in the spec the guarantee that,

this range-iterate-over clause with an implicit index iteration value, too, will always keep the same order as well:

for _, v := range []int{11, 22, 33, 44} {
    fmt.Println(v)
}

Will those two examples I put above always perform in the same order?

I assume they do but I haven't heard the promise yet.

How does for ... range work when the index iteration value is represented by the blank identifier(the underscore _)?

  • 写回答

1条回答 默认 最新

  • dongza1708 2019-02-04 09:37
    关注

    It's in the spec, but I think you overlook something. There are iteration values and iteration variables.

    For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.

    And your quote refers to iteration values:

    For an array, pointer to array, or slice value a, the index iteration values are produced in increasing order, starting at element index 0. If at most one iteration variable is present, the range loop produces iteration values from 0 up to len(a)-1 and does not index into the array or slice itself.

    So as you can see, regardless of how many iteration variables there are, the iteration values are always in increasing order, starting at element index 0.

    And the second iteration value is always a[i], where i corresponds to the first iteration value, the index:

    Range expression                          1st value          2nd value
    
    array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置