Goroutines in Go
Start concurrent work with the go keyword and wait for it to finish with sync.WaitGroup.
A goroutine is a function running at the same time as the rest of your program. Starting one takes a single keyword, and waiting for a group of them takes a sync.WaitGroup. This section covers both.
Starting Goroutines
go say("background")
go starts the call in a new goroutine and moves on immediately. The program ends when main returns, so goroutines that have not finished are stopped.
time.Sleep is not a way to wait:
Sleeping in main only hopes the goroutines are done. Use a WaitGroup or a channel to know they are.
Waiting with sync.WaitGroup
Add(1) before each go, defer wg.Done() inside, and Wait() to block until all are done. Never copy a WaitGroup, and remember sync: negative WaitGroup counter means Done was called too often.
Summary
Goroutines are cheap to start, but every one needs a way to finish and someone waiting for it. These two pages give you both halves.
Starting Goroutines in Go
What a goroutine is, how the go keyword starts one, why main can exit before your goroutines finish, and how goroutines differ from threads.
Waiting for Goroutines with sync.WaitGroup
How sync.WaitGroup works, the Add, Done and Wait rules, the panic messages you get when they are misused, and collecting results safely.