// Chapter 37 example: several goroutines send their results to one channel. // Run with: go run exercises/37/06-collect.go package main import ( "fmt" "time" ) // result is what one download sends back. type result struct { name string bytes int } // download pretends to fetch a file. Longer names take longer. func download(name string) result { time.Sleep(time.Duration(len(name)) * 100 * time.Millisecond) return result{name: name, bytes: len(name) * 1000} } func main() { start := time.Now() files := []string{"notes.txt", "a.txt", "photo.png", "song.mp3"} results := make(chan result) for _, name := range files { go func() { results <- download(name) }() } total := 0 for range len(files) { r := <-results fmt.Printf("%-10s %5d bytes\n", r.name, r.bytes) total += r.bytes } fmt.Println("Total:", total, "bytes in", time.Since(start).Round(100*time.Millisecond)) }