The correct way to save the first error of multiple goroutines using a mutex

1 day ago 1
ARTICLE AD BOX

I'm writing a function that gets student grades in parallel goroutines and returns their arithmetic mean at the end. If at least one student has an error, the function should return the first error that occurred.

How to properly handle this error? There might be some issues. I need to first define mu.Lock() for the error and defer mu.Unlock() for sum.

func Average(names []string) (int, error) { mu := &sync.Mutex{} wg := &sync.WaitGroup{} sum := 0 var firstErr error for _, name := range names { wg.Add(1) go func(n string) { defer wg.Done() elem, err := GetMarks(n) mu.Lock() defer mu.Unlock() if err != nil { if firstErr == nil { firstErr = err } return } sum += elem mu.Unlock() }(name) } wg.Wait() if firstErr != nil { return 0, firstErr } if len(names) == 0 { return 0, nil } return sum / len(names), nil }
Read Entire Article