From 0cab7d52d5ffaa23f31dfcabf61662a6581d1edb Mon Sep 17 00:00:00 2001
From: Rob Pike v
may have been modified since the goroutine was launched.
-To bind the value of v
to each closure as they are launched, one
-could modify the inner loop to read:
+To bind the current value of v
to each closure as it is launched, one
+must modify the inner loop to create a new variable each iteration.
+One way is to pass the variable as an argument to the closure:
@@ -1239,6 +1240,21 @@ anonymous function. That value is then accessible inside the function as the variableu
. ++Even easier is just to create a new variable, using a declaration style that may +seem odd but works fine in Go: +
+ ++ for _, v := range values { + v := v // create a new 'v'. + go func() { + fmt.Println(v) + done <- true + }() + } ++Control flow