Junior — Middle
Can you explain what Errgroup is and how it is used to manage a group of goroutines in Go?
sobes.tech AI
Answer from AI
Errgroup is a package in Go that simplifies managing a group of goroutines, allowing to run multiple parallel tasks and collect their errors. It provides an easy way to wait for all goroutines to finish and get the first error if any.
Main features of Errgroup:
- Launch multiple goroutines using
Go(func() error)method. - Wait for all goroutines to complete via
Wait(), which returns the first error or nil.
Example usage:
import (
"golang.org/x/sync/errgroup"
"fmt"
)
func main() {
var g errgroup.Group
urls := []string{"http://example.com", "http://golang.org", "http://invalid.url"}
for _, url := range urls {
url := url // capture variable
g.Go(func() error {
// code here, e.g., HTTP request
fmt.Println("Fetching", url)
// return error if needed
return nil
})
}
if err := g.Wait(); err != nil {
fmt.Println("Error in goroutines:", err)
} else {
fmt.Println("All goroutines completed successfully")
}
}
Thus, Errgroup helps manage parallel tasks and handle errors in Go.