Track Goroutines With The WaitGroup Go Method
Track workers with the WaitGroup Go method added in Go 1.25, which starts each closure in a goroutine and joins it, replacing manual Add and Done calls.
Code
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
results := make([]int, 3)
// Go 1.25 新增的 WaitGroup.Go 方法(method):
// 一句 wg.Go 等价于 Add(1) + go func(){ ...; Done() },
// 启动与回收不再手工配对,也就不会漏掉 Done
for i := 0; i < 3; i++ {
wg.Go(func() {
results[i] = (i + 1) * (i + 1)
})
}
wg.Wait()
fmt.Println("squares:", results)
}The program in motion
Count the function main as the entire surface area of Track Goroutines With The WaitGroup Go Method.
A single loop drives the file — for i := 0; i < 3; i++.
Applying it
Running the file prints labeled results such as squares: — each operation’s effect is visible in the output.
Statements that matter
results := make([]int, 3)
var 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 Track Goroutines With The WaitGroup Go Method print when run?
- Execute the whole file; each printed line is prefixed with a label like `squares:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.