sync.WaitGroup blocks the main goroutine until all launched goroutines call Done() to signal completion.
Use sync.WaitGroup to wait for a collection of goroutines to finish by incrementing the counter before launching them and calling Done() when they complete.
var wg sync.WaitGroup
wg.Add(2)
for i := 0; i < 2; i++ {
go func(id int) {
defer wg.Done()
// do work
}(i)
}
wg.Wait()
A WaitGroup acts like a counter that tracks how many background tasks are still running. You tell it how many tasks to expect, and it pauses your main program until every single task signals it is finished. Think of it as a project manager who won't leave the office until every employee has clocked out.