liveBook · Manning

Errgroup.Group

As explained in Learn Go with Pocket-Sized Projects

errgroup.Group is a Go synchronization type that coordinates goroutines and reports an error from a failed goroutine.

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:

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains group creation, concurrency limits, goroutine registration, waiting, and returned errors through a runnable example.
Examples
Uses concurrent rice and curry preparation, including a task that may return an error.
What it assumes
Assumes familiarity with Go goroutines and introduces synchronization through comparison with channels and sync.WaitGroup.
What you can do after
Apply it via golang.org/x/sync/errgroup to limit parallel work and handle a goroutine error at a synchronization point.
How it connects
Connects goroutines with sync.WaitGroup, channels, and concurrent error handling.

Also explained in

Compare how 2 books explain errgroup.Group →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.