Explanation
What just happened
SetLimit(2) gave the group two slots. Jobs 1 and 2 took them, so the third g.Go didn’t return: main itself waited until a job finished. Then jobs 3 and 4 ran, and g.Wait waited for all four.
Try the what-if switch
- a job fails: job 2 fails at once. That cancels
ctx, job 1 stops early, jobs 3 and 4 start already cancelled, andg.Waitreturns job 2’s error.
Why
A plain go statement starts as many goroutines as you ask for. A thousand jobs that each open a connection can overload the server they call. SetLimit makes the loop wait instead.
When to use it
For many independent jobs that can fail, where you want the first error and the rest stopped: fetching a list of URLs, processing files. For results, collect them as in getting results back from goroutines.
Watch out
g.Go blocks its caller, as it blocked main here. If that goroutine has other work to do, TryGo never waits: it returns false when every slot is taken.
Common questions
How do I limit how many goroutines run at once?
Use errgroup.Group with SetLimit(n). At most n jobs run at once; past that, g.Go blocks the goroutine that calls it, in [chan send], until a job finishes and frees a slot.
What does g.Wait return when a job fails?
The first error. With errgroup.WithContext, that error also cancels the group's context, and g.Wait still returns the first error, not the cancellations it caused.
Does a failing job stop the other goroutines?
Only if they watch ctx.Done(). WithContext cancels the context; a plain errgroup.Group cancels nothing, and its other jobs run to the end.
What's the difference between g.Go and g.TryGo?
g.Go waits for a free slot. g.TryGo doesn't: with every slot taken, it returns false and starts nothing.
Verified: this timeline matches a real program, checked in CI on Go 1.26 and 1.27. How we verify. Unclear or wrong? Tell us