WaitGroup.Go in Go
Go 1.25 added Go, which does the Add and Done for you.
func square(values []int) []int {
results := make([]int, len(values))
var wg sync.WaitGroup
for i, value := range values {
wg.Go(func() {
results[i] = value * value // each index is written once
})
}
wg.Wait()
return results
}
How it works
wg.Go(f)replaces Add, a goroutine and a deferred Done.Waitstill blocks until every task has finished.- Results still need a channel or a mutex; the group only counts.
Keywords and builtins used here
forfuncintlenmakerangereturnvar
The run, in numbers
- Lines
- 13
- Characters to type
- 228
- Tokens
- 66
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 42 seconds.
Step 2 of 3 in Goroutines, step 2 of 25 in Concurrency.