From 0cab7d52d5ffaa23f31dfcabf61662a6581d1edb Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Fri, 7 Sep 2012 09:11:39 -0700 Subject: [PATCH] faq: another way to solve the closure/variable/range complaint It's easier just to declare a new variable. R=golang-dev, bradfitz CC=golang-dev https://golang.org/cl/6501103 --- doc/go_faq.html | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/doc/go_faq.html b/doc/go_faq.html index 8264e1940a8..ea6edc37e90 100644 --- a/doc/go_faq.html +++ b/doc/go_faq.html @@ -1220,8 +1220,9 @@ but 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 variable u.
 

+

+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