go · level 3 · unit 5 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two lines fail. Which one is reported?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import (
"fmt"
"strconv"
"sync"
)
func main() {
lines := []string{"8", "x", "5", "y"}
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()
for i, err := range errs {
if err != nil {
fmt.Println("first bad line:", i+1)
break
}
}
}
your turn
Your turn. Wrap the error with its row number.
Type an age that is not a number for row 2. Then fill in the fmt.Errorf verb that wraps an error, so errors.Is can still find the cause.
output
press run to see what happens
fix it
The bad line vanishes from the report. Can you fix it?
output
press run to see what happens
oopsis not a number, yet the report never mentions it. Where does its error go?nums[i], _ =throws the error away with_, so its slot inerrsstays nil.- Keep it instead:
nums[i], errs[i] = strconv.Atoi(line).
nailed it
no error is lost on the way home. :D
- Give every job a slot for its error.
- Report partial failures plainly, and never drop an error with
_. - The first error means first by job order.
new words in your collection
- partial failure
This lesson isn’t saved. A free account remembers every lesson you finish.