From: Rob Pike Date: Fri, 21 Sep 2012 19:55:04 +0000 (+1000) Subject: [release-branch.go1] faq: another way to solve the closure/variable/range complaint X-Git-Tag: go1.0.3~36 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=0809931b2f3fe52338af686188f9e4c5cdede96b;p=gostls13.git [release-branch.go1] faq: another way to solve the closure/variable/range complaint ««« backport 3bca7b333e00 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 »»» --- diff --git a/doc/go_faq.html b/doc/go_faq.html index 8264e1940a..ea6edc37e9 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