golang 切片和数组在for...range中的区别
切片是引用类型,而数组是值类型,并且for...range有以下规则:
- range表达式只会在for语句开始执行时被求值一次,无论后边会有多少次迭代
- range表达式的求值结果会被复制,也就是说,被迭代的对象是range表达式结果值的副本而不是原值
package main
import (
"fmt"
)
func main() {
numbers2 := [...]int{1, 2, 3, 4, 5, 6}
maxIndex2 := len(numbers2) - 1
for i, e := range numbers2 {
if i == maxIndex2 {
numbers2[0] += e
} else {
numbers2[i+1] += e
}
}
fmt.Println(numbers2)
numbers3 := []int{1, 2, 3, 4, 5, 6}
maxIndex2 = len(numbers3) - 1
for i, e := range numbers3 {
if i == maxIndex2 {
numbers3[0] += e
} else {
numbers3[i+1] += e
}
}
fmt.Println(numbers3)
}
打印结果
[7 3 5 7 9 11]
[22 3 6 10 15 21]