Explain it simply
Explain it simply
This lesson is harder than the first Exercises lesson. It revisits three ideas from the Advanced chapter, interfaces, custom errors and goroutines with channels, with one exercise each, and the mini challenge then combines all three.
Picture a restaurant kitchen. Order slips are the jobs channel, three cooks are the worker goroutines, and the pass where finished plates go is the results channel. Dishes finish in a different order than they were ordered, so each plate is matched back to its table by the slip number. In a worker pool, that slip number is an index.
Problem → Why → Solution
The problem: it has an Error() method, yet it is not an error
When people try exercise 2, they often write Error() with a pointer receiver and then return a plain struct value from validateAge. The compiler rejects it with "InvalidAgeError does not implement error (method Error has pointer receiver)".
The message is puzzling at first, because the Error() method is right there. The answer lies in method sets: the method exists, but it belongs to the pointer type *InvalidAgeError, not to the value type InvalidAgeError.
type InvalidAgeError struct{ Age int }
func (e *InvalidAgeError) Error() string { return "invalid age" }
func validateAge(age int) error {
if age < 0 || age > 150 {
return InvalidAgeError{Age: age} // compile error: Error has pointer receiver
}
return nil
}What is a method set?
The method set of a type T contains only its value-receiver methods, while the method set of *T contains both value- and pointer-receiver methods. To satisfy an interface, every required method must be in the method set. So returning &InvalidAgeError{Age: age} compiles; writing Error() with a value receiver would make both forms work.
The ideas behind the three exercises
1. Interfaces are satisfied implicitly
Circle and Rectangle never declare "implements Shape". Having an Area() float64 method is enough to be a Shape, so they can sit together in a []Shape, and s.Area() runs each value's own method. %T shows the concrete type actually stored in the interface, such as main.Circle.
2. A custom error carries data
errors.New can only hold a message, while InvalidAgeError also carries the rejected Age. The caller declares var ageErr *InvalidAgeError and calls errors.As(err, &ageErr), which searches the wrapped chain for that type and fills in ageErr. The target must be a pointer to the type that implements error, here itself a pointer.
3. The close() order in a worker pool
Each worker takes jobs with for i := range jobs. When the producer has sent every job it calls close(jobs), so the worker loops end and each calls wg.Done(). A closer goroutine calls close(results) only after wg.Wait(), which ends the loop reading results. Only the sending side ever closes a channel.
4. Restore the order with an index
The order in which goroutines finish depends on the scheduler and can change on every run. Sending the index rather than the number as the job, and getting back result{index, square}, lets the collector write out[r.index]. Whatever order results arrive in, the output is always the same.
Worker pool with an ordered collector
-------------------------------------
producer --i--> [jobs] --+--> worker 1 --+
close(jobs) after last |--> worker 2 --+--> [results] --> out[r.index]
+--> worker 3 --+ ^
wg.Wait() then close(results)| Receiver of Error() | Types that satisfy error |
|---|---|
| (e InvalidAgeError) | Both InvalidAgeError and *InvalidAgeError |
| (e *InvalidAgeError) | Only *InvalidAgeError |
One question keeps coming back in all three exercises: who owns this value? An interface value holds a concrete type plus a value, and an error value belongs to the caller who receives it. A channel belongs to the goroutine that sends on it, so only that goroutine may close it. When ownership is clear, most deadlocks and data races can be avoided before you write a line of code.
- Send indexes into jobs
- Workers take and compute
- Send back result{index, value}
- Store it in out[index]
For every channel, decide up front who closes it: the one who knows that all sending is finished.
General pattern
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for job := range jobs {
results <- process(job)
}
}()
}
go func() { feed(jobs); close(jobs) }()
go func() { wg.Wait(); close(results) }()
for r := range results { collect(r) }Start N workers, let a producer send every job and close jobs, close results only after all workers finish, and collect results in a loop.
Three solved exercises
Areas use math.Pi and are printed to two decimal places with %.2f. validateAge is tried with one valid and one invalid age, and errors.As pulls the Age field back out. squareAll squares ten numbers on three workers, but because results are placed by index, every run prints the same output.
package main
import (
"errors"
"fmt"
"math"
"sync"
)
// Exercise 1: one interface, two shapes
type Shape interface {
Area() float64
}
type Circle struct{ Radius float64 }
type Rectangle struct{ Width, Height float64 }
func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius }
func (r Rectangle) Area() float64 { return r.Width * r.Height }
// Exercise 2: a custom error type
type InvalidAgeError struct{ Age int }
func (e *InvalidAgeError) Error() string {
return fmt.Sprintf("invalid age %d (must be 0-150)", e.Age)
}
func validateAge(age int) error {
if age < 0 || age > 150 {
return &InvalidAgeError{Age: age}
}
return nil
}
// Exercise 3: a worker pool that keeps results in input order
type result struct{ index, square int }
func squareAll(nums []int, workers int) []int {
jobs := make(chan int)
results := make(chan result)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
results <- result{i, nums[i] * nums[i]}
}
}()
}
go func() {
for i := range nums {
jobs <- i
}
close(jobs) // ends every worker's range loop
}()
go func() {
wg.Wait()
close(results) // ends the collector's range loop below
}()
out := make([]int, len(nums))
for r := range results {
out[r.index] = r.square
}
return out
}
func main() {
shapes := []Shape{Circle{Radius: 2}, Rectangle{Width: 3, Height: 4}}
total := 0.0
for _, s := range shapes {
fmt.Printf("%T area: %.2f\n", s, s.Area())
total += s.Area()
}
fmt.Printf("total area: %.2f\n", total)
for _, age := range []int{30, 200} {
err := validateAge(age)
var ageErr *InvalidAgeError
if errors.As(err, &ageErr) {
fmt.Println("rejected", ageErr.Age, "->", err)
} else {
fmt.Println("accepted", age)
}
}
nums := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Println("squares:", squareAll(nums, 3))
}Code breakdown
- Mixed shapes, one slice
shapes := []Shape{Circle{Radius: 2}, Rectangle{Width: 3, Height: 4}}Circle and Rectangle both have Area(), so both fit in a []Shape. The loop calls s.Area() without knowing which type it holds.
- Return the pointer
return &InvalidAgeError{Age: age}Error() has a pointer receiver, so only *InvalidAgeError can be returned as an error. Dropping the & is a compile error.
- Read the data back
if errors.As(err, &ageErr) {If err holds a *InvalidAgeError, errors.As stores it in ageErr and returns true, so ageErr.Age can be used directly. For a nil err it returns false and the code takes the "accepted" branch.
- The producer closes jobs
close(jobs) // ends every worker's range loopjobs is closed only after every index has been sent. Without it, the workers wait in range jobs forever and the program deadlocks.
- Close results after the workers
close(results) // ends the collector's range loop belowwg.Wait() waits for all workers before results is closed. Doing this in a separate goroutine lets main read results at the same time, so nothing blocks even though the channel is unbuffered.
- Order restored
out[r.index] = r.squareEach result lands at its own index whatever order it arrives in, so out follows the input order.
main.Circle area: 12.57
main.Rectangle area: 12.00
total area: 24.57
accepted 30
rejected 200 -> invalid age 200 (must be 0-150)
squares: [1 4 9 16 25 36 49 64 81 100]A buffer can hide a deadlock
You will often see worker pools that use a buffered channel, results := make(chan int, 10), and call wg.Wait() in main before reading any results. With ten jobs and a buffer of ten, the workers drop every result into the buffer and finish, so it works.
The day there are eleven jobs, one worker cannot send because the buffer is full, main is stuck in wg.Wait() so nobody is reading, and the program deadlocks. The closer-goroutine shape in the example works for any number of jobs.
In real projects
In real projects
Worker pools show up wherever there is a lot of CPU or network work: generating image thumbnails, checking hundreds of URLs, hashing many files. The number of workers caps how much runs at once, which stops you from flooding a server with requests. When results are shown to a user, putting them back in order by index, as in this lesson, matters.
Custom error types are everywhere in the standard library too. *fs.PathError carries the operation and the path that failed, and *json.SyntaxError carries the byte offset where the JSON went wrong. Callers pull those fields out with errors.As to show a detailed message. Health-check tools work the same way, carrying each check's name and reason inside an error type so a dashboard can display them.
Common mistakes
Common mistakes
Forgetting close(jobs)
If jobs is never closed, the workers keep waiting in range jobs and wg.Wait() never returns. When every goroutine is stuck, the runtime stops with "fatal error: all goroutines are asleep - deadlock!". In a program where other goroutines keep running, such as a server, that message never appears and the workers silently leak instead.
Returning a typed nil pointer as an error
Declaring var e *InvalidAgeError, assigning it only on failure and ending with return e makes err != nil even for a valid age. The interface value holds a type (*InvalidAgeError), so it is not nil even though the pointer inside is. On success, write return nil explicitly.
Calling wg.Add inside the worker
With go func() { wg.Add(1); ... }(), main can reach wg.Wait() before the goroutine has even started, see a counter of 0 and return at once. Call wg.Add(1) before the go statement.
Best practices
Best practices
- Always try concurrent code with go run -race and run it several times.
- Give channel parameters a direction, <-chan or chan<-, so the compiler catches a worker that tries to close jobs.
- Pass the worker count as a parameter instead of hard-coding it; for CPU-bound work, runtime.NumCPU() is a good starting point.
Mini challenge
Build a health-check runner
Write two kinds of checks, disk and ping, that implement a Checker interface, and run all of them concurrently on two workers. A failing check returns a *CheckError with a reason, and main prints the reason using errors.As. The output must come out in the same order on every run.
- The Checker interface has Name() string and Check() error
- DiskCheck fails when FreeGB < 5 and PingCheck when LatencyMs > 200, returning a *CheckError
- runChecks(checks, workers) returns a []error in the same order as the checks (nil means healthy)
- main prints one OK or FAIL line per check, then a summary such as "2/4 checks healthy"
package main
import (
"errors"
"fmt"
"sync"
)
type Checker interface {
// TODO: Name() string and Check() error
}
type CheckError struct{ Name, Reason string }
// TODO: give *CheckError an Error() method: "name: reason"
type DiskCheck struct{ FreeGB int }
type PingCheck struct {
Host string
LatencyMs int
}
// TODO: Name() and Check() for DiskCheck and PingCheck
// runChecks returns one error per check, in the checks' order.
func runChecks(checks []Checker, workers int) []error {
// TODO: jobs channel of indexes, workers write errs[i], WaitGroup
}
func main() {
checks := []Checker{
DiskCheck{FreeGB: 120}, PingCheck{Host: "db", LatencyMs: 12},
DiskCheck{FreeGB: 2}, PingCheck{Host: "cdn", LatencyMs: 450},
}
// TODO: print OK/FAIL per check (errors.As), then "x/4 checks healthy"
fmt.Println(len(checks), "checks to run")
}Expected: OK disk, OK ping db, FAIL disk - only 2 GB free and FAIL ping cdn - 450 ms is too slow, in the checks' order, then 2/4 checks healthy.
Show hint
Each worker writes only its own errs[i], a different index every time, so no mutex is needed, and reading errs after wg.Wait() sees every write. You do not even need a results channel.
Show solution
package main
import (
"errors"
"fmt"
"sync"
)
type Checker interface {
Name() string
Check() error
}
type CheckError struct {
Name, Reason string
}
func (e *CheckError) Error() string { return e.Name + ": " + e.Reason }
type DiskCheck struct{ FreeGB int }
func (d DiskCheck) Name() string { return "disk" }
func (d DiskCheck) Check() error {
if d.FreeGB < 5 {
return &CheckError{d.Name(), fmt.Sprintf("only %d GB free", d.FreeGB)}
}
return nil
}
type PingCheck struct {
Host string
LatencyMs int
}
func (p PingCheck) Name() string { return "ping " + p.Host }
func (p PingCheck) Check() error {
if p.LatencyMs > 200 {
return &CheckError{p.Name(), fmt.Sprintf("%d ms is too slow", p.LatencyMs)}
}
return nil
}
// runChecks runs every check on a pool of workers and returns the errors
// in the same order as the checks (nil means healthy).
func runChecks(checks []Checker, workers int) []error {
errs := make([]error, len(checks))
jobs := make(chan int)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
errs[i] = checks[i].Check() // one writer per index
}
}()
}
for i := range checks {
jobs <- i
}
close(jobs)
wg.Wait()
return errs
}
func main() {
checks := []Checker{
DiskCheck{FreeGB: 120},
PingCheck{Host: "db", LatencyMs: 12},
DiskCheck{FreeGB: 2},
PingCheck{Host: "cdn", LatencyMs: 450},
}
healthy := 0
for i, err := range runChecks(checks, 2) {
var ce *CheckError
switch {
case err == nil:
healthy++
fmt.Println("OK ", checks[i].Name())
case errors.As(err, &ce):
fmt.Println("FAIL", ce.Name, "-", ce.Reason)
default:
fmt.Println("ERR ", err)
}
}
fmt.Printf("%d/%d checks healthy\n", healthy, len(checks))
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Interfaces are satisfied implicitly, and pointer-receiver methods belong only to *T
- A custom error type carries data; read it back with errors.As
- The sender closes jobs; results is closed only after wg.Wait()
- Placing concurrent results by index makes the output identical on every run
- On success write return nil, never a typed nil pointer
A Tour of Go — Go