Golang / GoLang Concurrency Mastery Interview Questions
How does golang.org/x/sync/errgroup simplify concurrent error handling?
errgroup.Group is a higher-level abstraction over sync.WaitGroup that adds automatic error collection and optional context cancellation. It is the idiomatic tool for the pattern of running N goroutines and returning the first non-nil error.
import "golang.org/x/sync/errgroup" // Basic errgroup â collect first error func fetchAll(urls []string) error { g := new(errgroup.Group) for _, url := range urls { url := url // capture for goroutine (pre-Go 1.22) g.Go(func() error { resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() return nil }) } return g.Wait() // waits for all; returns first non-nil error } // errgroup with context â cancel all on first error func fetchWithCancel(ctx context.Context, urls []string) error { g, gctx := errgroup.WithContext(ctx) // gctx is cancelled when any goroutine returns an error for _, url := range urls { url := url g.Go(func() error { req, _ := http.NewRequestWithContext(gctx, "GET", url, nil) resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() return nil }) } return g.Wait() } // Limit concurrency (Go 1.20+) g.SetLimit(10) // max 10 goroutines â g.Go blocks when at limit for _, url := range urls { url := url g.Go(func() error { return fetch(url) }) }
More Related questions...