title: WaitGroup goroutines with channel
body: <p>I am learning <code>WaitGroup</code> from the blog <a href="https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/" rel="nofollow noreferrer">https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/</a></p>
  
  <p>the code:</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "sync"
      "time"
  )
  
  func main() {
      messages := make(chan int)
      var wg sync.WaitGroup
  
      // you can also add these one at 
      // a time if you need to 
  
      wg.Add(3)
      go func() {
          defer wg.Done()
          time.Sleep(time.Second * 3)
          messages &lt;- 1
      }()
      go func() {
          defer wg.Done()
          time.Sleep(time.Second * 2)
          messages &lt;- 2
      }() 
      go func() {
          defer wg.Done()
          time.Sleep(time.Second * 1)
          messages &lt;- 3
      }()
      go func() {
          for i := range messages {
              fmt.Println(i)
          }
      }()
  
      wg.Wait()
  }
  </code></pre>
  
  <p>I think it should print 3, 2 and 1 in order. But it only prints 3, 2 but 1 is missing, what's the problem?</p>
  
  <p>You can tree it on <a href="https://play.golang.org/p/kZCvDhykYM" rel="nofollow noreferrer">https://play.golang.org/p/kZCvDhykYM</a></p>