Created
September 10, 2017 11:07
-
-
Save hadv/0d357f31d8b4b570c539a7f8a8819533 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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