mirror of
https://github.com/golang/go
synced 2024-11-24 14:00:15 -07:00
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
This commit is contained in:
parent
acbe6c94d7
commit
0cab7d52d5
@ -1220,8 +1220,9 @@ but <code>v</code> may have been modified since the goroutine was launched.
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
To bind the value of <code>v</code> to each closure as they are launched, one
|
To bind the current value of <code>v</code> to each closure as it is launched, one
|
||||||
could modify the inner loop to read:
|
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:
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<pre>
|
<pre>
|
||||||
@ -1239,6 +1240,21 @@ anonymous function. That value is then accessible inside the function as
|
|||||||
the variable <code>u</code>.
|
the variable <code>u</code>.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
|
<p>
|
||||||
|
Even easier is just to create a new variable, using a declaration style that may
|
||||||
|
seem odd but works fine in Go:
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<pre>
|
||||||
|
for _, v := range values {
|
||||||
|
<b>v := v</b> // create a new 'v'.
|
||||||
|
go func() {
|
||||||
|
fmt.Println(<b>v</b>)
|
||||||
|
done <- true
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
</pre>
|
||||||
|
|
||||||
<h2 id="Control_flow">Control flow</h2>
|
<h2 id="Control_flow">Control flow</h2>
|
||||||
|
|
||||||
<h3 id="Does_Go_have_a_ternary_form">
|
<h3 id="Does_Go_have_a_ternary_form">
|
||||||
|
Loading…
Reference in New Issue
Block a user