Comment by a-poor

Comment by a-poor 12 hours ago

2 replies

This means you can't pass variables in as function arguments. Even the example in the official go docs doesn't handle the scope correctly:

  func main() {
   var wg sync.WaitGroup
   var urls = []string{
    "http://www.golang.org/",
    "http://www.google.com/",
    "http://www.example.com/",
   }
   for _, url := range urls {
    // Launch a goroutine to fetch the URL.
    wg.Go(func() {
     // Fetch the URL.
     http.Get(url)
    })
   }
   // Wait for all HTTP fetches to complete.
   wg.Wait()
  }
https://pkg.go.dev/sync#example-WaitGroup

You need to use this pattern instead:

   for _, url := range urls {
    url := url
    // ...
9rx 12 hours ago

> This means you can't pass variables in as function arguments.

Well, you could...

    for _, url := range urls {
        wg.Go(func(u string) func() {
            return func() {
                http.Get(u)
            }
        }(url))
    }
> You need to use this pattern instead

Why? Seems rather redundant. It is not like WaitGroup.Go exists in earlier versions.