谁能解释一下,这段代码运行既不报错,也不是死循环。
```go
m := map[int]string{
1: "a",
2: "b",
3: "c",
}
for k, v := range m {
m[k*k] = m[k] + m[k]
fmt.Println("k: ", k, "\tv: ", v)
}
fmt.Println(m)
```
第 1 条附言 ·
```go
m := map[int]string{
1: "a",
2: "b",
3: "c",
4: "d",
5: "e",
}
for k, v := range m {
m[k+5] = m[k] + m[k]
fmt.Println("k: ", k, "\tv: ", v)
}
fmt.Println(m)
```
运行输出结果:
```
k: 1 v: a
k: 2 v: b
k: 3 v: c
k: 4 v: d
k: 5 v: e
k: 6 v: aa
k: 7 v: bb
k: 8 v: cc
map[10:ee 11:aaaa 12:bbbb 1:a 2:b 6:aa 9:dd 8:cc 13:cccc 3:c 4:d 5:e 7:bb]
```
第 2 条附言 ·
下面2段代码输出结果一样:
```go
s := []int{1, 2, 3}
for i, v := range s {
s = append(s, s[i]+3)
fmt.Println("i: ", i, "\tv: ", v)
}
fmt.Println(s)
```
```go
s := make([]int, 3, 100)
s[0], s[1], s[2] = 1, 2, 3
for i, v := range s {
s = append(s, s[i]+3)
fmt.Println("i: ", i, "\tv: ", v)
}
fmt.Println(s)
```
运行输出结果:
```
i: 0 v: 1
i: 1 v: 2
i: 2 v: 3
[1 2 3 4 5 6]
```
第 3 条附言 ·
```go
s := []int{1, 2, 3}
for i, v := range s {
s = s[0:2]
fmt.Println("i: ", i, "\tv: ", v)
}
fmt.Println(s)
```
运行输出结果:
```
i: 0 v: 1
i: 1 v: 2
i: 2 v: 3
[1 2]
```
The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.
From:
https://golang.org/ref/spec
#7
更多评论