Skip to content

Instantly share code, notes, and snippets.

@hadv
Created September 10, 2017 11:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadv/0d357f31d8b4b570c539a7f8a8819533 to your computer and use it in GitHub Desktop.
Save hadv/0d357f31d8b4b570c539a7f8a8819533 to your computer and use it in GitHub Desktop.
func (w multiWeatherProvider) temperature(city string) (float64, error) {
// Make a channel for temperatures, and a channel for errors.
// Each provider will push a value into only one.
temps := make(chan float64, len(w))
errs := make(chan error, len(w))
// For each provider, spawn a goroutine with an anonymous function.
// That function will invoke the temperature method, and forward the response.
for _, provider := range w {
go func(p weatherProvider) {
k, err := p.temperature(city)
if err != nil {
errs <- err
return
}
temps <- k
}(provider)
}
sum := 0.0
// Collect a temperature or an error from each provider.
for i := 0; i < len(w); i++ {
select {
case temp := <-temps:
sum += temp
case err := <-errs:
return 0, err
}
}
// Return the average, same as before.
return sum / float64(len(w)), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment