Parallel Results Written By Index
Preallocate one result slot per input so each goroutine writes only its own index: disjoint writes need no mutex and order matches the input slice.
Code
package main
import (
"fmt"
"sync"
)
// 结果按输入下标预分配:每个 goroutine 只写自己的 results[i],
// 下标互不相交即无数据竞争,顺序天然与输入一致,无需锁或通道。
// Go 1.22+ 循环变量每轮独立,闭包捕获 i/n 是安全的。
func parallelSquares(nums []int) []int {
results := make([]int, len(nums))
var wg sync.WaitGroup
for i, n := range nums {
wg.Add(1)
go func() {
defer wg.Done()
results[i] = n * n
}()
}
wg.Wait()
return results
}
func main() {
nums := []int{2, 3, 5, 7, 11}
fmt.Println(parallelSquares(nums))
fmt.Println("len matches:", len(parallelSquares(nums)))
}How the snippet works
The callable surface is the functions parallelSquares and main — everything else is wiring.
Iteration happens inside for i, n := range nums — everything outside it runs once. The task is handed to a goroutine and runs concurrently. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.
Using it
Signature: func parallelSquares(nums []int) []int
The demo output is labeled (len matches:), so the printed lines read as a trace of the operations that ran.
The sequence parallelSquares lives in main; running the file triggers it.
Key statements
for i, n := range nums {
wg.Add(1)
go func() {
defer wg.Done()
results[i] = n * n
}()
}
func main() {
nums := []int{2, 3, 5, 7, 11}
fmt.Println(parallelSquares(nums))
fmt.Println("len matches:", len(parallelSquares(nums)))
}
results := make([]int, len(nums))
Interactive Tools for This Topic
FAQ
- What does Parallel Results Written By Index print when run?
- Invoke the file as-is — the `len matches:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.