How to Use errgroup for Concurrent Tasks in Go

Use errgroup.WithContext and g.Go to run concurrent tasks that cancel automatically on the first error.

Use errgroup.WithContext to create a group and context, then call g.Go for each task and g.Wait to block until completion or the first error.

package main

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"time"
)

func main() {
	ctx := context.Background()
	g, ctx := errgroup.WithContext(ctx)

	for i := 0; i < 3; i++ {
		i := i // capture loop variable
		g.Go(func() error {
			select {
			case <-time.After(100 * time.Millisecond):
				return fmt.Errorf("task %d failed", i)
			case <-ctx.Done():
				return ctx.Err()
			}
		})
	}

	if err := g.Wait(); err != nil {
		fmt.Println("Error:", err)
	}
}