Go Playbook

Course › Week 2 · Methods, interfaces, errors, tests › Day 7 · lesson 14 of 42 · 20 min reading + 1–2 h practice

Week 2 checkpoint

go vet and staticcheck clean, every error checked, and every failure ends in a clear message.

go vetstaticcheckerrors

On this page
  1. 1. A counter that does not count
  2. 2. The waiting list that never opens
  3. 3. Extending a booking in a map
  4. 4. A notifier that almost fits
  5. 5. A test that cannot fail
  6. The logstat v2 exit check
  7. What PHP would have done
  8. Remember

Five broken programs, one for each idea of this week. Two do not compile; three compile and give a wrong answer, and one of those hides inside a test that passes.

For each: run it, say in one sentence what went wrong, then fix it. Write your sentence down before you open the answer. If any of them takes you more than 15 minutes, re-read that lesson before Week 3.

1. A counter that does not count

main.go
package main

import "fmt"

type Counter struct {
	Confirmed int
}

func (c Counter) Add() {
	c.Confirmed++
}

func main() {
	var counter Counter
	for i := 0; i < 3; i++ {
		counter.Add()
	}

	fmt.Println("confirmed:", counter.Confirmed)
}
staticcheck ./...
main.go:10:2: ineffective assignment to field Counter.Confirmed (SA4005)
$ go run .
confirmed: 0
Show the solution

One sentence: Add has a value receiver, so each call changed a copy of the counter and threw it away; staticcheck says the assignment is never seen.

The fix: a pointer receiver, because the method changes its value (the pointers lesson).

main.go
package main

import "fmt"

type Counter struct {
	Confirmed int
}

func (c *Counter) Add() {
	c.Confirmed++
}

func main() {
	var counter Counter
	for i := 0; i < 3; i++ {
		counter.Add()
	}

	fmt.Println("confirmed:", counter.Confirmed)
}
$ go run .
confirmed: 3

2. The waiting list that never opens

A guest asks for a fully booked flat and should be offered the waiting list:

main.go
package main

import (
	"errors"
	"fmt"
)

var ErrFullyBooked = errors.New("fully booked")

func reserve(property string) error {
	return fmt.Errorf("reserving %s: %v", property, ErrFullyBooked)
}

func main() {
	err := reserve("nyhavn")

	if errors.Is(err, ErrFullyBooked) {
		fmt.Println("offer the waiting list")
		return
	}
	if err != nil {
		fmt.Println("show an error page:", err)
	}
}
$ go run .
show an error page: reserving nyhavn: fully booked
Show the solution

One sentence: %v copied the sentinel’s text into the message but did not keep the error itself, so errors.Is found nothing in the chain.

The fix: %w (the error-wrapping lesson).

main.go
package main

import (
	"errors"
	"fmt"
)

var ErrFullyBooked = errors.New("fully booked")

func reserve(property string) error {
	return fmt.Errorf("reserving %s: %w", property, ErrFullyBooked)
}

func main() {
	err := reserve("nyhavn")

	if errors.Is(err, ErrFullyBooked) {
		fmt.Println("offer the waiting list")
		return
	}
	if err != nil {
		fmt.Println("show an error page:", err)
	}
}
$ go run .
offer the waiting list

3. Extending a booking in a map

main.godoes not compile
package main

import "fmt"

type Booking struct {
	Guest  string
	Nights int
}

func main() {
	bookings := map[int]Booking{
		1042: {Guest: "Astrid", Nights: 3},
	}

	bookings[1042].Nights++

	fmt.Println(bookings[1042])
}
go build
# hello
./main.go:15:2: cannot assign to struct field bookings[1042].Nights in map
Show the solution

One sentence: a map gives back a copy of the struct stored under a key, and changing a field of that temporary copy would be lost, so Go refuses.

The fix: store pointers, map[int]*Booking, when the values must be changed in place (the pointers lesson). The other fix is to read the struct, change it, and store it back: b := bookings[1042]; b.Nights++; bookings[1042] = b.

main.go
package main

import "fmt"

type Booking struct {
	Guest  string
	Nights int
}

func main() {
	bookings := map[int]*Booking{
		1042: {Guest: "Astrid", Nights: 3},
	}

	if b, ok := bookings[1042]; ok {
		b.Nights++
	}

	fmt.Println(*bookings[1042])
}
$ go run .
{Astrid 4}

With pointers in the map, a missing key gives nil, and nil.Nights panics. The comma-ok check guards against it.

4. A notifier that almost fits

main.godoes not compile
package main

import "fmt"

type Notifier interface {
	Notify(message string) error
}

type SlackNotifier struct {
	Channel string
}

func (s SlackNotifier) Notify(message string) {
	fmt.Printf("slack %s: %s\n", s.Channel, message)
}

func main() {
	var n Notifier = SlackNotifier{Channel: "#ops"}

	if err := n.Notify("booking 1042 failed to sync"); err != nil {
		fmt.Println(err)
	}
}
go build
# hello
./main.go:18:19: cannot use SlackNotifier{…} (value of struct type SlackNotifier) as Notifier value in variable declaration: SlackNotifier does not implement Notifier (wrong type for method Notify)
		have Notify(string)
		want Notify(string) error
Show the solution

One sentence: an interface matches on the whole signature, and this Notify returns nothing where the interface wants an error.

The fix: match the signature (the interfaces lesson). A real Slack notifier makes an HTTP call that can fail, so it needs to return an error anyway.

main.go
package main

import "fmt"

type Notifier interface {
	Notify(message string) error
}

type SlackNotifier struct {
	Channel string
}

func (s SlackNotifier) Notify(message string) error {
	fmt.Printf("slack %s: %s\n", s.Channel, message)
	return nil
}

func main() {
	var n Notifier = SlackNotifier{Channel: "#ops"}

	if err := n.Notify("booking 1042 failed to sync"); err != nil {
		fmt.Println(err)
	}
}
$ go run .
slack #ops: booking 1042 failed to sync

5. A test that cannot fail

Between(3, 7) should be 4 nights. The test passes:

nights/nights_test.gonew file
package nights

import "testing"

func TestBetween(t *testing.T) {
	tests := []struct {
		checkIn, checkOut, want int
	}{
		{checkIn: 3, checkOut: 7, want: 4},
		{checkIn: 1, checkOut: 2, want: 1},
	}

	for _, tt := range tests {
		got := Between(tt.checkIn, tt.checkOut)
		if got != tt.want {
			t.Logf("Between(%d, %d) = %d, want %d", tt.checkIn, tt.checkOut, got, tt.want)
		}
	}
}
$ go test
PASS
ok  	nights	0.002s
Show the solution

One sentence: t.Logf only writes a note, shown with -v; it does not mark the test as failed, so the test passed while Between was wrong.

The fix: t.Errorf (the tests lesson). Now the test fails, and shows the real bug: Between adds 1, counting days instead of nights.

nights/nights_test.gochanged since the version above: +1 −1
12 unchanged linespackage nights import "testing" func TestBetween(t *testing.T) { tests := []struct { checkIn, checkOut, want int }{ {checkIn: 3, checkOut: 7, want: 4}, {checkIn: 1, checkOut: 2, want: 1}, }
for _, tt := range tests { got := Between(tt.checkIn, tt.checkOut) if got != tt.want { t.Logf("Between(%d, %d) = %d, want %d", tt.checkIn, tt.checkOut, got, tt.want) t.Errorf("Between(%d, %d) = %d, want %d", tt.checkIn, tt.checkOut, got, tt.want) } }}
$ go test
--- FAIL: TestBetween (0.00s)
    nights_test.go:16: Between(3, 7) = 5, want 4
    nights_test.go:16: Between(1, 2) = 2, want 1
FAIL
exit status 1
FAIL	nights	0.002s

Then fix Between to return checkOut - checkIn, and the test passes for the right reason. The habit that catches this: make a new test fail once on purpose before you trust it passing.

The logstat v2 exit check

Before Week 3, your logstat from the build day must pass every line of this table.

CheckHow
The module path is your repository’s pathhead -1 go.mod shows module github.com/…/logstat
Parsing lives in internal/logparse, and main.go has no parsing codeRead main.go: flags, validation, run, exit codes.
count reads an io.Reader and is tested without a filegrep -n "os.Open" stats.go prints nothing
Every rejected line from your real logs is a test caseAdd the ones you met; they are the next regression.
-min LOUD and an unknown flag exit with 2, a missing file with 1./logstat -min LOUD x.log; echo $?
Errors passed up use %wSearch for %v next to an err: each one left is there on purpose.
gofmt -l ., go vet ./... and staticcheck ./... print nothing; go test ./... passesRun all four.
Installablego install github.com/…/logstat@latest on another machine

What PHP would have done

The same five mistakes in PHP:

MistakePHPGo
1. A method that changes a copyImpossible: $this is always the objectA value receiver changes a copy; staticcheck warns
2. Losing the causenew RuntimeException($e->getMessage()) without previous:: the same bug%v instead of %w
3. Changing a struct inside a mapArrays of arrays: changes a copy silently, or works with &Compile error
4. A method that almost fits an interfaceFatal error when the class is loaded, if it says implementsCompile error where the value is used as the interface
5. A test that cannot failAn assertion that is never reached: the same bugt.Logf instead of t.Errorf

Remember

  • A test you have never seen fail proves nothing: break the code once and watch it fail.

Week 3 starts with JSON: struct tags, and what happens to fields the JSON does not have.