比较两段代码:
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
for len(a) > 0 {
a = a[1:]
fmt.Println(a)
}
}
输出
[2 3 4 5 6 7 8 9]
[3 4 5 6 7 8 9]
[4 5 6 7 8 9]
[5 6 7 8 9]
[6 7 8 9]
[7 8 9]
[8 9]
[9]
[]
这是符合预期的,a一直在变化,for循环中len(a)也一直在变化
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
for _, v := range a {
fmt.Printf("v is %d\n", v)
a = a[:len(a)-1]
fmt.Println(a)
}
}
输出
v is 1
[1 2 3 4 5 6 7 8]
v is 2
[1 2 3 4 5 6 7]
v is 3
[1 2 3 4 5 6]
v is 4
[1 2 3 4 5]
v is 5
[1 2 3 4]
v is 6
[1 2 3]
v is 7
[1 2]
v is 8
[1]
v is 9
[]
可见range a中的a还是原数组
package main
import "fmt"
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
for i := 0; i < len(a); i++ {
v := a[i]
fmt.Printf("v is %d\n", v)
a = a[:len(a)-1]
fmt.Println(a)
}
}
输出
v is 1
[1 2 3 4 5 6 7 8]
v is 2
[1 2 3 4 5 6 7]
v is 3
[1 2 3 4 5 6]
v is 4
[1 2 3 4 5]
v is 5
[1 2 3 4]
可以看出不用for range,是不会存在这种问题的