title: Go concurrency with for loop and anonymous function behaves unexpectedly
body: <p>I have already found out a way for the code to behave as I want, but I would like to understand why it behaves like this so that my understanding of Go concurrency improves.</p>
  
  <p>I was testing out <code>sync.WaitGroup</code> to wait for some goroutines to finish because I plan on doing multiple uploads to Amazon S3 in this way.</p>
  
  <p>This was the code I had originally:</p>
  
  <pre><code>func main() {
  
      var wg sync.WaitGroup
  
      for i := 1; i &lt;= 5; i++ {
          wg.Add(1)
          go func() {
              fmt.Println(i)
              time.Sleep(time.Second * 1)
              wg.Done()
          }()
      }
  
      wg.Wait()
  }
  </code></pre>
  
  <p>I was surprised to see that the output was: <code>6, 6, 6, 6, 6</code>.</p>
  
  <p>Instead of something like: <code>2, 4, 1, 5, 3</code>.</p>
  
  <p>Since the loop does not even go to 6, this made no sense to me.
  I later passed the <code>i</code> variable to the anonymous function as argument
  and then it behaved as I expected.</p>
  
  <p>Why does this happen? I don't understand it.</p>