WaitGroup Go Starts And Joins Goroutines
WaitGroup Go starts each goroutine with Add and Done already handled, so fan-out code becomes a single closure call before one Wait joins everything.
Code
package main
import (
"fmt"
"slices"
"sync"
)
func squares(ids []int) []int {
var (
wg sync.WaitGroup
mu sync.Mutex
results []int
)
for _, id := range ids {
// Go 1.25 的 WaitGroup.Go:内部先 Add(1),闭包返回后自动 Done
wg.Go(func() {
mu.Lock()
results = append(results, id*id)
mu.Unlock()
})
}
wg.Wait()
return results
}
func main() {
sq := squares([]int{2, 5, 9})
// goroutine 完成顺序不定,展示前先排序
slices.Sort(sq)
fmt.Println("squares:", sq)
}Inside the snippet
WaitGroup Go Starts And Joins Goroutines keeps everything in the functions squares and main.
The cycling part of this snippet is for _, id := range ids.
Using it
The main signature, verbatim, is func squares(ids []int) []int
The demo output is labeled (squares:), so the printed output reads as a trace of the operations performed.
Execute the file and main walks through squares, in that order.
Key statements
for _, id := range ids {
// Go 1.25 的 WaitGroup.Go:内部先 Add(1),闭包返回后自动 Done
wg.Go(func() {
mu.Lock()
results = append(results, id*id)
mu.Unlock()
})
}
func main() {
sq := squares([]int{2, 5, 9})
// goroutine 完成顺序不定,展示前先排序
slices.Sort(sq)
fmt.Println("squares:", sq)
}
wg sync.WaitGroup
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does WaitGroup Go Starts And Joins Goroutines print when run?
- Run it as a complete program — the output lines carry labels such as `squares:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.