×

go · level 3 · unit 5 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Give every job an error slot, so no failure goes missing.

A goroutine cannot return an error to main; they are separate. So bring errors home the same way as results: an error slot per job, or a result struct holding both a value and an error. A worker fills its slot, and main reads them all after Wait.

Some jobs work and some fail. That is a , and a good tool says so plainly: report what failed, count it, and never throw an error away with _.

If you report the first error, make it the first by job order, not the first to arrive. Arrival order changes from run to run; job order does not.

package main
import (
	"fmt"
	"strconv"
	"sync"
)
func main() {
	lines := []string{"12", "seven", "30", "4x"}
	errs := make([]error, len(lines))
	var wg sync.WaitGroup
	for i, line := range lines {
		wg.Add(1)
		go func(i int, line string) { defer wg.Done(); _, errs[i] = strconv.Atoi(line) }(i, line)
	}
	wg.Wait()
	failed := 0
	for i, err := range errs {
		if err != nil {
			failed++
			fmt.Printf("line %d: %v\n", i+1, err)
		}
	}
	fmt.Println(failed, "of", len(lines), "lines failed")
}

_, errs[i] = strconv.Atoi(line) drops the number, which this check does not need, and keeps the error.