Skip to content

Instantly share code, notes, and snippets.

@kennethzfeng
Created September 6, 2015 14:37
Show Gist options
  • Select an option

  • Save kennethzfeng/7ea387e3a3b5c7ca67c8 to your computer and use it in GitHub Desktop.

Select an option

Save kennethzfeng/7ea387e3a3b5c7ca67c8 to your computer and use it in GitHub Desktop.
Golang Gotchas
package main
import (
"fmt"
"sync"
)
func main() {
wg := &sync.WaitGroup{}
for _, v := range []int{1, 4, 7} {
v := v
wg.Add(1)
go func() {
fmt.Println(v)
wg.Done()
}()
}
wg.Wait()
}
package main
import (
"fmt"
"sync"
)
func main() {
wg := &sync.WaitGroup{}
for _, v := range []int{1, 4, 7} {
wg.Add(1)
go func() {
fmt.Println(v)
wg.Done()
}()
}
wg.Wait()
}
@christophberger
Copy link

Another right.go:

package main

import (
    "fmt"
    "sync"
)

func main() {
    wg := &sync.WaitGroup{}

    for _, v := range []int{1, 4, 7} {
        wg.Add(1)
        go func(n int) {
            fmt.Println(n)
            wg.Done()
        }(v)
    }

    wg.Wait()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment