liveBook · Manning

Errgroup.WithContext

As explained in 100 Go Mistakes and How to Avoid Them

errgroup.WithContext creates an errgroup.Group associated with a context and returns a derived context canceled when the group encounters an error or finishes waiting.

A common mistake is pairing sync.WaitGroup with an unfinished error strategy. Shared error slices, mutexes, or error channels add coordination work; errgroup.WithContext combines synchronization, first-error propagation, and context cancellation. section 9.13

func handler(ctx context.Context, circles []Circle) ([]Result, error) {
    results := make([]Result, len(circles))
    g, ctx := errgroup.WithContext(ctx)      #1
 
    for i, circle := range circles {
        i := i
        circle := circle
        g.Go(func() error {                  #2
            result, err := foo(ctx, circle)
            if err != nil {
                return err
            }
            results[i] = result
            return nil
        })
    }
 
    if err := g.Wait(); err != nil {         #3
        return nil, err
    }
    return results, nil
}

Use errgroup.WithContext to derive a context, start one g.Go call per circle, return errors from each closure, and retrieve the first non-nil error with g.Wait. section 9.13

Pass the derived context to each operation when a fast failure should make remaining work cancelable. Return results only after g.Wait succeeds; otherwise return the error immediately. section 9.13

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains the API, its two methods, error flow, and shared-context cancellation through a concrete handler implementation.
Examples
Uses a handler that invokes foo concurrently for a slice of circles and stores results by index.
What it assumes
Assumes familiarity with goroutines, contexts, closures, and waiting for concurrent work.
What you can do after
Apply it via golang.org/x/sync/errgroup to simplify parallel calls with coordinated errors and cancellation.
How it connects
Connects goroutines, contexts, synchronization, error propagation, and cancellation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.