Analysis of go for range pits and closure pits
- 2020-06-23 00:38:42
- OfStack
See the program:
package main
import (
"fmt"
"time"
)
func main() {
str := []string{"I","like","Golang"}
for _, v := range str{
v += "good"
}
for k, v := range str{
fmt.Println(k, v)
}
time.Sleep(1e9)
}
Results:
[
0 I
1 like
2 Golang
Think 1 think why.
Then look at:
package main
import (
"fmt"
"time"
)
func main() {
str := []string{"I","like","Golang"}
for k, v := range str{
fmt.Println(&k, &v)
}
time.Sleep(1e9)
}
Results:
[
0xc000012050 0xc00000e1e0
0xc000012050 0xc00000e1e0
0xc000012050 0xc00000e1e0
Think 1 think why.
Then look at:
package main
import (
"fmt"
"time"
)
func main() {
str := []string{"I","like","Golang"}
for k, v := range str{
str = append(str, "good")
fmt.Println(k, v)
}
time.Sleep(1e9)
}
Results:
[
0 I
1 like
2 Golang
Think 1 think why.
Then look at:
package main
import (
"fmt"
"time"
)
func main() {
str := []string{"I","like","Golang"}
for k, v := range str{
go func(i int, s string){
fmt.Println(i, s, k, v)
}(k, v)
}
time.Sleep(1e9)
}
Results:
[
0 I 2 Golang
1 like 2 Golang
2 Golang 2 Golang
Think 1 think why.
Finally:
package main
import (
"fmt"
"time"
)
func main() {
str := []string{"I","like","Golang"}
for k, v := range str{
go func(i int, s string){
fmt.Println(i, s, k, v)
}(k, v)
time.Sleep(1e9)
}
time.Sleep(5e9)
}
Results:
[
0 I 0 I
1 like 1 like
2 Golang 2 Golang
Think 1 think why.
Not much said.
conclusion