I'm trying to loop through a list (e.g. sql rows) and fire go routines for each row. The issue is that the values passed to the function are not evaluated at the runtime so depending by how much time the function takes to execute it may use whatever value is on one of the next(s) rows instead the current one.
I'm aware that I could extract the function in a normal one and pass the arguments but I still want to share some global variables(to avoid many function arguments) thus the need to use an anonymous function. Still it's also confusing to me that the anonymous function takes variables from the environment while it's being executed because as far as I understand it is supposed to be executed in a separate routines just like & in unix programs, the communication being done only through channels.
The question is how do I make the anonymous function to receive a copy of vc
and use it during runtime ?
package main
import "fmt"
import "time"
type mystruct struct {
i int
s string
}
func main() {
vc := mystruct{}
vc.i = 1
vc.s = "hi"
gl := "this is global"
for i := 1; i < 4; i++ {
go func() {
vc.i++
time.Sleep(1 * time.Second)
fmt.Printf("row specific is %v, global is %v", vc, gl)
}()
}
time.Sleep(2 * time.Second)
}