From 0809931b2f3fe52338af686188f9e4c5cdede96b Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Sat, 22 Sep 2012 05:55:04 +1000 Subject: [release-branch.go1] faq: another way to solve the closure/variable/range complaint MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ««« 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 »»» --- 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 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

-- cgit v1.2.3-54-g00ecf