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

隐含索引时,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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化