News for hackers. Stuff that matters.
Re:Waitgroups: What they are, how to use them and what chang... by a-poor on Saturday August 23, 2025 @12:58PM (#44997268)
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
    // ...
Re:Waitgroups: What they are, how to use them and what chang... by jeremyloy_wt on Saturday August 23, 2025 @01:01PM (#44997301)
This isn’t necessary anymore as of Go 1.22

https://go.dev/blog/loopvar-preview

Re:Waitgroups: What they are, how to use them and what chang... by 9rx on Saturday August 23, 2025 @01:10PM (#44997396)
> 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.