← All Exercises

Cancel Siblings on First Error

advancedgo~35min

Background

Fan-out work often becomes pointless after the first failure; an errgroup combines WaitGroup synchronization with context cancellation and first-error capture.

Problem

Implement Group with WithContext(parent), Go(fn), and Wait(). The first non-nil error cancels the shared context, later errors are ignored, Wait blocks until every goroutine returns, and Wait returns the first error or nil.

Input

A parent context and several task functions that accept the group context.

Output

The first error returned by any task, or nil when all tasks succeed; Wait returns only after all tasks finish.

Sample tests

Sample 1

Input: one task returns errors.New("boom"), another waits for ctx.Done()
Expected: boom

Sample 2

Input: two tasks return nil
Expected: <nil>

Your solution

Learning objective

Combine WaitGroup, context cancellation, and sync.Once into a reusable error group.