gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:25:27 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com