print.go (1038B)
1 package main 2 3 import ( 4 "fmt" 5 "sync" 6 7 "github.com/dwrz/talks/concurrency/pkg/weather" 8 ) 9 10 const ( 11 // Hardcoded padding for longest city name, Philadelphia. 12 message = "%-12s %.2f°F\n" 13 ) 14 15 func printTemperatures(cities []string) { 16 for _, city := range cities { 17 cityWeather, err := weather.GetCity(city) 18 if err != nil { 19 fmt.Printf( 20 "error getting weather for %s: %v\n", city, err, 21 ) 22 continue 23 } 24 25 fmt.Printf(message, city, cityWeather.Temp) 26 } 27 } 28 29 func printTemperaturesAsync(cities []string) { 30 var weatherReports = make(chan string, len(cities)) 31 var wg sync.WaitGroup 32 wg.Add(len(cities)) 33 34 for _, city := range cities { 35 go func(city string) { 36 defer wg.Done() 37 38 cityWeather, err := weather.GetCity(city) 39 if err != nil { 40 fmt.Printf( 41 "error getting weather for %s: %v\n", 42 city, err, 43 ) 44 return 45 } 46 47 weatherReports <- fmt.Sprintf( 48 message, city, cityWeather.Temp, 49 ) 50 }(city) 51 } 52 53 wg.Wait() 54 close(weatherReports) 55 56 for report := range weatherReports { 57 fmt.Print(report) 58 } 59 }