Goroutines WaitGroup Collect Results
Fan out work to goroutines, collect each result through a buffered channel, and join the workers with a WaitGroup so the channel drains fully before printing.
Code
package main
import (
"fmt"
"strings"
"sync"
)
func fetch(id int) string {
return fmt.Sprintf("item-%d", id)
}
func main() {
results := make(chan string, 4) // 缓冲与任务数相同:worker 永不阻塞
var wg sync.WaitGroup
for id := 1; id <= 4; id++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
results <- fetch(n)
}(id)
}
// 所有 worker 返回后关闭 channel,让 range 自然结束
go func() {
wg.Wait()
close(results)
}()
// 交付顺序由完成先后决定:谁先做完谁先到,这正是并发性
for got := range results {
fmt.Println("got:", strings.ToUpper(got))
}
fmt.Println("all workers joined")
}Tracing the logic
Goroutines WaitGroup Collect Results comes down to the functions fetch and main.
The one repetition in this snippet is the loop for id := 1; id <= 4; id++. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Putting it to use
Signature: func fetch(id int) string
Running the file prints labeled results such as got:, all workers joined — each operation’s effect is visible in the output.
Execute the file and main walks through fetch, in that order.
Core lines
return fmt.Sprintf("item-%d", id)
for got := range results {
fmt.Println("got:", strings.ToUpper(got))
}
go func(n int) {
defer wg.Done()
results <- fetch(n)
}(id)
Interactive Tools for This Topic
FAQ
- What does Goroutines WaitGroup Collect Results print when run?
- The script runs standalone; its 2 labeled outputs include `got:`, `all workers joined`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.