title: Why does Go handle closures differently in goroutines?
body: <p>Consider the following Go code (also on the <a href="http://play.golang.org/p/Hmc46TwCCv" rel="noreferrer">Go Playground</a>):</p>
  <pre><code>package main
  
  import &quot;fmt&quot;
  import &quot;time&quot;
  
  func main() {
      for _, s := range []string{&quot;foo&quot;, &quot;bar&quot;} {
          x := s
          func() {
              fmt.Printf(&quot;s: %s\n&quot;, s)
              fmt.Printf(&quot;x: %s\n&quot;, x)
          }()
      }
      fmt.Println()
      for _, s := range []string{&quot;foo&quot;, &quot;bar&quot;} {
          x := s
          go func() {
              fmt.Printf(&quot;s: %s\n&quot;, s)
              fmt.Printf(&quot;x: %s\n&quot;, x)
          }()
      }
      time.Sleep(time.Second)
  }
  </code></pre>
  <p>This code produces the following output:</p>
  <pre><code>s: foo
  x: foo
  s: bar
  x: bar
  
  s: bar
  x: foo
  s: bar
  x: bar
  </code></pre>
  <p>Assuming this isn't some odd compiler bug, I'm curious why a) the value of s is interpreted differently in the goroutine version then in the regular func call and b) and why assigning it to a local variable inside the loop works in both cases.</p>