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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等