Go Playbook

Course › Week 3 · Real data and speed › Day 7 · lesson 21 of 42 · 20 min reading + 1–2 h practice

Week 3 checkpoint

Flat memory on a 1M-row file, and bad rows never stop the run.

streamingmemory

On this page
  1. 1. The score that never reaches the API
  2. 2. The export that is always empty
  3. 3. A webhook that books zero nights
  4. 4. A sum for any type
  5. 5. A filter that changed its mind
  6. The csv2json exit check
  7. What PHP would have done
  8. Remember

Five broken programs from this week. One does not compile. The other four run without an error and give a wrong or an empty answer, which is what data bugs look like in production: nothing crashes, and the numbers are wrong.

For each: run it, say in one sentence what went wrong, then fix it. Then put csv2json through its exit check, including the memory test on a million rows.

1. The score that never reaches the API

main.go
package main

import (
	"encoding/json/v2"
	"fmt"
	"os"
)

type Answer struct {
	Question string `json:"question"`
	score    int
}

func main() {
	data, err := json.Marshal(Answer{Question: "q1", score: 5})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(string(data))
}
$ go run .
{"question":"q1"}
Show the solution

One sentence: score starts with a lowercase letter, so it is unexported and the json package cannot see it; it was dropped without an error.

The fix: export it and name it in a tag (the JSON lesson). A test that compares the exact JSON output, as csv2json’s does, catches this the first time it runs.

main.go
package main

import (
	"encoding/json/v2"
	"fmt"
	"os"
)

type Answer struct {
	Question string `json:"question"`
	Score    int    `json:"score"`
}

func main() {
	data, err := json.Marshal(Answer{Question: "q1", Score: 5})
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(string(data))
}
$ go run .
{"question":"q1","score":5}

2. The export that is always empty

main.go
package main

import (
	"encoding/csv"
	"fmt"
	"os"
)

func main() {
	writer := csv.NewWriter(os.Stdout)

	for _, row := range [][]string{{"evaluation_id", "average"}, {"9001", "4.50"}} {
		if err := writer.Write(row); err != nil {
			fmt.Fprintln(os.Stderr, "writing a row:", err)
			os.Exit(1)
		}
	}
}
$ go run .

The output is empty, and the exit code is 0.

Show the solution

One sentence: csv.Writer buffers rows in memory, and nothing flushed the buffer before the program ended, so the rows were never written.

The fix: Flush, then check Error (the CSV lesson). The same goes for every bufio.Writer.

main.go
package main

import (
	"encoding/csv"
	"fmt"
	"os"
)

func main() {
	writer := csv.NewWriter(os.Stdout)

	for _, row := range [][]string{{"evaluation_id", "average"}, {"9001", "4.50"}} {
		if err := writer.Write(row); err != nil {
			fmt.Fprintln(os.Stderr, "writing a row:", err)
			os.Exit(1)
		}
	}

	writer.Flush()
	if err := writer.Error(); err != nil {
		fmt.Fprintln(os.Stderr, "writing the CSV:", err)
		os.Exit(1)
	}
}
$ go run .
evaluation_id,average
9001,4.50

3. A webhook that books zero nights

The channel manager sends {"booking_id": 1042, "nights": 3}:

main.go
package main

import (
	"encoding/json/v2"
	"fmt"
	"os"
)

type Webhook struct {
	BookingID int `json:"booking_id"`
	Nights    int `json:"Nights"`
}

func main() {
	var hook Webhook
	if err := json.Unmarshal([]byte(`{"booking_id": 1042, "nights": 3}`), &hook); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Printf("booking %d: %d nights\n", hook.BookingID, hook.Nights)
}
$ go run .
booking 1042: 0 nights
Show the solution

One sentence: v2 matches member names exactly, so the tag Nights does not match nights; the member was ignored and the field kept its zero value.

The fix: the tag must match the JSON (the JSON lesson). For an API you control, also reject unknown members: then this mistake is an error, not a silent 0.

main.go
package main

import (
	"encoding/json/v2"
	"fmt"
	"os"
)

type Webhook struct {
	BookingID int `json:"booking_id"`
	Nights    int `json:"nights"`
}

func main() {
	var hook Webhook
	if err := json.Unmarshal([]byte(`{"booking_id": 1042, "nights": 3}`), &hook); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Printf("booking %d: %d nights\n", hook.BookingID, hook.Nights)
}
$ go run .
booking 1042: 3 nights

4. A sum for any type

main.godoes not compile
package main

import "fmt"

func Sum[T any](values []T) T {
	var total T
	for _, v := range values {
		total += v
	}
	return total
}

func main() {
	fmt.Println(Sum([]int{3, 7, 2}))
}
go build
# hello
./main.go:8:3: invalid operation: operator + not defined on total (variable of type T constrained by any)
Show the solution

One sentence: any allows every type, including ones that cannot be added, so the compiler refuses + inside the function even though the call uses int.

The fix: a constraint that lists types with + (the generics lesson). cmp.Ordered would work too, because strings can be added; a Number constraint says what is meant.

main.go
package main

import "fmt"

type Number interface {
	~int | ~int64 | ~float64
}

func Sum[T Number](values []T) T {
	var total T
	for _, v := range values {
		total += v
	}
	return total
}

func main() {
	fmt.Println(Sum([]int{3, 7, 2}))
}
$ go run .
12

5. A filter that changed its mind

The report keeps answers scoring 3 or more, then a second report wants 5 only:

main.go
package main

import (
	"fmt"
	"slices"
)

func main() {
	scores := []int{5, 4, 3, 2}

	minimum := 3
	passes := func(score int) bool { return score >= minimum }

	minimum = 5
	excellent := func(score int) bool { return score >= minimum }

	fmt.Println("passing:  ", slices.DeleteFunc(slices.Clone(scores), func(s int) bool { return !passes(s) }))
	fmt.Println("excellent:", slices.DeleteFunc(slices.Clone(scores), func(s int) bool { return !excellent(s) }))
}
$ go run .
passing:   [5]
excellent: [5]

slices.DeleteFunc removes the elements for which the function returns true, in place, so each report works on its own slices.Clone of the scores.

Show the solution

One sentence: both closures share the one variable minimum, so changing it to 5 changed the first filter too; “passing” lost the 4 and the 3.

The fix: give each filter its own copy of the value, by making the filters with a function that takes it as a parameter (the closures lesson).

main.go
package main

import (
	"fmt"
	"slices"
)

// atLeast returns a filter that keeps scores of at least minimum. Each call has its own minimum.
func atLeast(minimum int) func(int) bool {
	return func(score int) bool { return score >= minimum }
}

func main() {
	scores := []int{5, 4, 3, 2}

	passes := atLeast(3)
	excellent := atLeast(5)

	fmt.Println("passing:  ", slices.DeleteFunc(slices.Clone(scores), func(s int) bool { return !passes(s) }))
	fmt.Println("excellent:", slices.DeleteFunc(slices.Clone(scores), func(s int) bool { return !excellent(s) }))
}
$ go run .
passing:   [5 4 3]
excellent: [5]

The csv2json exit check

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

CheckHow
Memory stays flat on a 1M-row fileGenerate 1M rows with generate.php, then compare the peak memory of a 100K and a 1M run: on Linux /usr/bin/time -v ./csv2json … (“Maximum resident set size”), on macOS /usr/bin/time -l. They should be within a few MB.
Bad rows never stop the runEvery rejected row is in the errors file with its line and reason, and the JSON has the rest.
Too many bad rows is a failureA file of only bad rows exits with 1.
An Excel export worksSave a sample from Excel as “CSV UTF-8” and run it.
Identical to the PHP versioncmp on both outputs and both error files prints nothing.
Every writer is flushed and every written file closed with its error checkedRead convert.go and run.
gofmt -l ., go vet ./... and staticcheck ./... print nothing; go test ./... passesRun all four.

What PHP would have done

The same five mistakes in PHP:

MistakePHPGo
1. A private fieldjson_encode skips private properties too: the same bugUnexported fields are skipped
2. A buffer never flushedfputcsv writes through PHP’s stream buffer, flushed at exitNothing written without Flush
3. A key with the wrong case$data['Nights'] is null, (int) null is 0: the same bugExact matching: the field stays 0
4. Adding values of any type$total += $v works, or throws a TypeError at runtimeA compile error until the constraint allows +
5. A closure seeing a later changeuse ($minimum) copies: no bug; use (&$minimum) shares: the same bugClosures always share

Remember

  • Data bugs do not crash: compare exact output in tests, flush every writer, and match JSON names exactly.

Week 4 starts with goroutines: running work at the same time, and waiting for all of it.