typestar

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

  1. wg.Go(f) replaces Add, a goroutine and a deferred Done.
  2. Wait still blocks until every task has finished.
  3. Results still need a channel or a mutex; the group only counts.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Goroutines, step 2 of 25 in Concurrency.

← Previous Next →