Hacker Newsnew | past | comments | ask | show | jobs | submit | a-poor's commentslogin

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
    // ...


This isn’t necessary anymore as of Go 1.22

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


> 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.


I would love to -- I'm planning to start with something on the smaller side as a PoC.


Delve into the world of Rust development with this blog post on creating a custom URL shortener, complete with tech stack analysis, middleware integration, and load testing.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: