errgroup.Group coordinates goroutines and reports an error when one of them fails. It provides a compact alternative to pairing sync.WaitGroup with an error channel. section 7.2.4 section 7.6
Use the group in three steps:
- Create an errgroup.Group value. section 7.2.4
- Call SetLimit(n) to set the maximum number of parallel goroutines. section 7.2.4 section 7.6
- Launch work with Go(func() error) and call Wait(); Wait returns an error if a goroutine returns one. section 7.2.4 section 7.6
Cooking rice and curry concurrently
var g errgroup.Group g.SetLimit(2) g.Go(func() error { cookRice() return nil }) g.Go(cookCurry) if err := g.Wait(); err != nil { // handle the failed task } Here, cookCurry returns an error while cookRice uses a closure that returns nil. section 7.2.4
Listing 7.7 Cooking example using sync.WaitGroup
package main
import (
"fmt"
"sync"
)
func main() {
wg := &sync.WaitGroup{} #1
wg.Add(2) #2
go cookRice(wg) #3
go cookCurry(wg) #3
wg.Wait() #4
}
func cookRice(wg *sync.WaitGroup) {
defer wg.Done() #5
fmt.Println("Cooking rice...")
// prepare rice
}
func cookCurry(wg *sync.WaitGroup) {
defer wg.Done() #5
fmt.Println("Preparing curry sauce...")
// prepare curry
}
Inspect the complete cooking example showing group creation, a concurrency limit, goroutine launch, and error handling. section 7.2.4

