for-loop - 索引隐式时 `for ... range`的迭代顺序

标签 for-loop go slice specifications

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.

根据规范,在 Go 中迭代线性数据结构(数组或 slice 或字符串)将始终按照索引递增的顺序获取其中的每个元素。

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

但问题是我无法在规范中真正找到保证,

这个带有隐式索引迭代值的 range-iterate-over 子句也将始终保持相同的顺序:

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

我上面给出的这两个例子是否总是以相同的顺序执行?

我想他们会这样做,但我还没有听到 promise 。

当索引迭代值由空白标识符(下划线 _)表示时,for ... range 如何工作?

最佳答案

它在规范中,但我认为您忽略了一些东西。有迭代值迭代变量

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

并且您的引用是指迭代值:

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.

因此如您所见,无论有多少迭代变量,迭代值始终按递增顺序排列,从元素索引 0 开始。

而第二次迭代的值总是a[i],其中i对应第一次迭代的值,索引:

Range expression                          1st value          2nd value

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E

关于for-loop - 索引隐式时 `for ... range`的迭代顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512586/

相关文章:

javascript - Jquery Onload 函数停止 for 循环,在函数内部传递 for 循环 x

go - 如何防止我的整个表被删除

python - 计算满足条件的列部分的平均值以创建新的数据框

php - 将时间范围分割成多个部分

javascript - iMacros 中的嵌套循环(第二个循环)

javascript - 在 JavaScript For 循环期间更新 DOM

html - 使用 for 循环或 lapply 将 Web 抓取到具有相似 URL 的 R 多个链接

go - 如何在遵守接口(interface)上的 golang CodeReviewComments 规则的同时执行正确的构造?

file-upload - 如何使用os.Open()的返回值作为http.Post()的第三个参数并设置Content-Length?

ruby - 在 Ruby 中从末尾切片字符串