Junior — Middle
Have you ever used the ErrGroup structure in your projects to manage parallel tasks?
sobes.tech AI
Answer from AI
Yes, the errgroup.Group structure from the golang.org/x/sync/errgroup package is often used for managing concurrent tasks.
It allows running multiple goroutines, collecting errors, and waiting for all tasks to complete. This is convenient when you need to perform several independent operations in parallel and handle errors centrally.
Example of usage:
import (
"context"
"golang.org/x/sync/errgroup"
)
func fetchData(ctx context.Context) error {
g, ctx := errgroup.WithContext(ctx)
urls := []string{"url1", "url2", "url3"}
for _, url := range urls {
url := url // local copy for closure
g.Go(func() error {
// code to load data from url
return nil // or error
})
}
if err := g.Wait(); err != nil {
return err
}
return nil
}
Thus, errgroup simplifies parallel execution with error control and cancellation via context.