当前位置:主页 > 脚本语言 > Golang >

go for range坑和闭包坑的分析

时间:2022-03-01 10:18:49 | 栏目:Golang | 点击:

看程序:

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)
}

结果:

0 I
1 like
2 Golang

想一想,为什么。

再看:

package main
import (
  "fmt"
  "time"
)
func main() {
  str := []string{"I","like","Golang"}
  for k, v := range str{
   fmt.Println(&k, &v)
  }
  time.Sleep(1e9)
}

结果:

0xc000012050 0xc00000e1e0
0xc000012050 0xc00000e1e0
0xc000012050 0xc00000e1e0

想一想,为什么。

再看:

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)
}

结果:

0 I
1 like
2 Golang

想一想, 为什么。

再看:

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)
}

结果:

0 I 2 Golang
1 like 2 Golang
2 Golang 2 Golang

想一想,为什么。

最后再看:

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)
}

结果:

0 I 0 I
1 like 1 like
2 Golang 2 Golang

想一想,为什么。

不多说。

总结

您可能感兴趣的文章:

相关文章