Understand the contract

A sync.WaitGroup tracks completion of a set of tasks. Add the task count before launching work, call Done when each task finishes and call Wait where the owner needs completion. A WaitGroup communicates completion, not results, and does not by itself serialize concurrent access to a map or counter.

Using defer wg.Done at the start of the goroutine keeps completion attached to every return path. Pass input as an argument when that makes ownership clear. The example uses the established Add/Done pattern; modern Go versions also provide other helpers, but the lifecycle rule remains explicit here.

Work through the example

Three tasks print their identifiers and main waits until all have called Done. Their output order is intentionally unspecified. The final message appears after completion. A test should check that all expected results exist, not require the workers to print in launch order.

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    for id := 1; id <= 3; id++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            fmt.Println("worker", id)
        }(id)
    }
    wg.Wait()
    fmt.Println("all complete")
}

Watch this boundary

Calling Add inside a newly launched goroutine can race logically with Wait observing a zero count. Calling Done too many times panics. Also avoid copying a WaitGroup after use; pass a pointer or capture the same instance when coordinating work across functions.

Practice with a changed input

Add an early return to one worker and confirm that deferred Done still lets Wait finish. Then collect results through a channel instead of asserting a particular print order.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services