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.

GoData Integrity

Code

gosnippet
23 lines
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

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:`.