title: How does Golang share variables between goroutines?
body: <p>I'm learning Go and trying to understand its concurrency features. </p>
  
  <p>I have the following program.</p>
  
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
      "fmt"
      "sync"
  )
  
  func main() {
      var wg sync.WaitGroup
  
      for i := 0; i &lt; 5; i++ {
          wg.Add(1)
  
          x := i
  
          go func() {
              defer wg.Done()
              fmt.Println(x)
          }()
  
      }
  
      wg.Wait()
      fmt.Println("Done")
  }
  </code></pre>
  
  <p>When executed I got:</p>
  
  <pre><code>4
  0
  1
  3
  2
  </code></pre>
  
  <p>It's just what I want. However, if I make slight modification to it:</p>
  
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
      "fmt"
      "sync"
  )
  
  func main() {
      var wg sync.WaitGroup
  
      for i := 0; i &lt; 5; i++ {
          wg.Add(1)
  
          go func() {
              defer wg.Done()
              fmt.Println(i)
          }()
  
      }
  
      wg.Wait()
      fmt.Println("Done")
  }
  </code></pre>
  
  <p>What I got will be:</p>
  
  <pre><code>5
  5
  5
  5
  5
  </code></pre>
  
  <p>I don't quite understand the difference. Can anyone help to explain what happened here and how Go runtime execute this code?</p>