-2

The following code results in an index out of range error. Intuitively I cans see it must be because the loop index is somehow global to the go routine, but I don't understand the details and would appreciate some insight.

package main

import "fmt"

func main() {
    t := [10]int{0,0,0,0,0,0,0,0,0,0}

    for i := 0; i < 10; i++{
        fmt.Println("Routine", i)
        go func(){
            test(&t, i)
        }()
    }
    fmt.Scanln()
}

func test(t *[10]int, i int){
    fmt.Println("testing", t[i])
}

  • get to read https://eli.thegreenplace.net/2019/go-internals-capturing-loop-variables-in-closures/ For reference, the spec says `Variables declared by the init statement are re-used in each iteration.` https://go.dev/ref/spec#For_statements – mh-cbon May 28 '22 at 17:14
  • 1
    I finally found this https://go.dev/doc/faq#closures_and_goroutines – mh-cbon May 28 '22 at 17:16
  • I found this https://yourbasic.org/golang/gotcha-data-race-closure/ answered my question . – Russell Maytham May 28 '22 at 19:35

0 Answers0