by a-poor · 1y ago · 0 comments
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-WaitGroupYou need to use this pattern instead:
for _, url := range urls {
url := url
// ...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 insteadWhy? Seems rather redundant. It is not like WaitGroup.Go exists in earlier versions.