Skip to content

Instantly share code, notes, and snippets.

@yumed15
Created November 28, 2023 10:07
Show Gist options
  • Save yumed15/30a7750559ec7323b38b4def048e5479 to your computer and use it in GitHub Desktop.
Save yumed15/30a7750559ec7323b38b4def048e5479 to your computer and use it in GitHub Desktop.
// you want to lookup the weather for multiple cities at once, and fail if any of the lookups fails.
func Cities(cities ...string) ([]*Info, error) {
var group errgroup.Group
var mu sync.Mutex
res := make([]*Info, len(cities)) // res[i] corresponds to cities[i]
for i, city := range cities {
i, city := i, city // create locals for closure below
group.Go(func() error {
info, err := City(city)
mu.Lock()
res[i] = info
mu.Unlock()
return err
})
}
if err := group.Wait(); err != nil {
return nil, err
}
return res, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment