WaitGroup Workers Aggregate Errors With Join
Each WaitGroup worker writes its result into a fixed slot, and errors.Join merges the non-nil errors into one value after all goroutines finish.
Code
package main
import (
"errors"
"fmt"
"sync"
)
func check(host string) error {
if len(host)%2 == 0 {
return fmt.Errorf("host %s: even length", host)
}
return nil
}
func main() {
hosts := []string{"a.example", "bb.example", "ccc.example"}
errs := make([]error, len(hosts))
var wg sync.WaitGroup
for i, host := range hosts {
wg.Add(1)
go func(slot int, h string) {
defer wg.Done()
errs[slot] = check(h) // 每个 worker 把结果写进固定槽位,互不重叠,无需互斥
}(i, host)
}
wg.Wait()
// errors.Join 忽略其中的 nil,把剩余错误合成一个;全 nil 返回 nil
if err := errors.Join(errs...); err != nil {
fmt.Println(err)
} else {
fmt.Println("all checks passed")
}
}Inside the snippet
WaitGroup Workers Aggregate Errors With Join keeps everything in the functions check and main.
The cycling part of this snippet is for i, host := range hosts. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly. Work is dispatched on a goroutine. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
- Error values are returned, not thrown — every call site must inspect
errbefore using the other return values.
Putting it to use
Entry signature: func check(host string) error
The run emits 1 labeled section — all checks passed — one per step.
main calls 1 helper in sequence: check.
The core lines, annotated
return fmt.Errorf("host %s: even length", host)
if err := errors.Join(errs...); err != nil {
fmt.Println(err)
} else {
fmt.Println("all checks passed")
}
go func(slot int, h string) {
defer wg.Done()
errs[slot] = check(h) // 每个 worker 把结果写进固定槽位,互不重叠,无需互斥
}(i, host)
Interactive Tools for This Topic
FAQ
- Does the snippet panic on failure?
- As returned `error` values — 1 site in the snippet check `err` before using other results.
- What does WaitGroup Workers Aggregate Errors With Join print when run?
- No setup needed: run the file and look for labeled lines like `all checks passed` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.