SoFunction
Updated on 2025-03-01

Analysis of go for range pit and closure pit

Look at 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{
   (k, v)
  }
  (1e9)
}

result:

0 I
1 like
2 Golang

Think about why.

Look again:

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

result:

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

Think about why.

Look again:

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

result:

0 I
1 like
2 Golang

Think about why.

Look again:

package main
import (
  "fmt"
  "time"
)
func main() {
  str := []string{"I","like","Golang"}
  for k, v := range str{
   go func(i int, s string){
    (i, s, k, v)
   }(k, v)
  }
  (1e9)
}

result:

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

Think about why.

Finally, 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){
    (i, s, k, v)
   }(k, v)
   (1e9)
  }
  (5e9)
}

result:

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

Think about why.

Not to say much.

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links