隐式索引时“for ... range”的迭代顺序
Iteration order of `for ... range` when the index is implicit
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 中迭代线性数据结构(数组或切片或字符串)将始终按照索引增加的顺序获取其中的每个元素。
for i, v := range []int{11, 22, 33, 44} {
fmt.Println(i, v)
}
但问题是我无法在规范中找到保证,
这个带有隐式索引迭代值的范围迭代子句也将始终保持相同的顺序:
for _, v := range []int{11, 22, 33, 44} {
fmt.Println(v)
}
我在上面举的那两个例子总是以相同的顺序执行吗?
我想他们会的,但我还没有听到承诺。
当索引迭代值由空白标识符(下划线_
)表示时,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
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 中迭代线性数据结构(数组或切片或字符串)将始终按照索引增加的顺序获取其中的每个元素。
for i, v := range []int{11, 22, 33, 44} {
fmt.Println(i, v)
}
但问题是我无法在规范中找到保证,
这个带有隐式索引迭代值的范围迭代子句也将始终保持相同的顺序:
for _, v := range []int{11, 22, 33, 44} {
fmt.Println(v)
}
我在上面举的那两个例子总是以相同的顺序执行吗?
我想他们会的,但我还没有听到承诺。
当索引迭代值由空白标识符(下划线_
)表示时,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 tolen(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