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.
On this page
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
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)
}
main.go:10:2: ineffective assignment to field Counter.Confirmed (SA4005)confirmed: 0Show 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).
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)
}
confirmed: 32. The waiting list that never opens
A guest asks for a fully booked flat and should be offered the waiting list:
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)
}
}
show an error page: reserving nyhavn: fully bookedShow 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).
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)
}
}
offer the waiting list3. Extending a booking in a map
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])
}
# hello
./main.go:15:2: cannot assign to struct field bookings[1042].Nights in mapShow 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.
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])
}
{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
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)
}
}
# 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) errorShow 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.
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)
}
}
slack #ops: booking 1042 failed to sync5. A test that cannot fail
Between(3, 7) should be 4 nights. The test passes:
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)
}
}
}
PASS
ok nights 0.002sShow 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.
12 unchanged lines
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) t.Errorf("Between(%d, %d) = %d, want %d", tt.checkIn, tt.checkOut, got, tt.want) } }}
--- 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.002sThen 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.
| Check | How |
|---|---|
| The module path is your repository’s path | head -1 go.mod shows module github.com/…/logstat |
Parsing lives in internal/logparse, and main.go has no parsing code | Read main.go: flags, validation, run, exit codes. |
count reads an io.Reader and is tested without a file | grep -n "os.Open" stats.go prints nothing |
| Every rejected line from your real logs is a test case | Add 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 %w | Search for %v next to an err: each one left is there on purpose. |
gofmt -l ., go vet ./... and staticcheck ./... print nothing; go test ./... passes | Run all four. |
| Installable | go install github.com/…/logstat@latest on another machine |
What PHP would have done
The same five mistakes in PHP:
| Mistake | PHP | Go |
|---|---|---|
| 1. A method that changes a copy | Impossible: $this is always the object | A value receiver changes a copy; staticcheck warns |
| 2. Losing the cause | new RuntimeException($e->getMessage()) without previous:: the same bug | %v instead of %w |
| 3. Changing a struct inside a map | Arrays of arrays: changes a copy silently, or works with & | Compile error |
| 4. A method that almost fits an interface | Fatal error when the class is loaded, if it says implements | Compile error where the value is used as the interface |
| 5. A test that cannot fail | An assertion that is never reached: the same bug | t.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.