What Is Structured Concurrency and How Go Approaches It

Structured concurrency ensures child goroutines finish with their parent, implemented in Go using WaitGroup and Context.

Structured concurrency is a programming model where a parent goroutine waits for all its child goroutines to finish before it exits, ensuring no goroutines are left running after the parent completes. Go does not enforce this automatically but provides primitives like sync.WaitGroup and context.Context to implement it manually.

var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())

wg.Add(1)
go func() {
    defer wg.Done()
    // do work
}()

wg.Wait()
cancel()