Course › Week 1 · Basics and a first CLI › Day 7 · lesson 7 of 42 · 20 min reading + 1–2 h practice
Week 1 checkpoint
Five broken programs to fix and explain. Pass them all before Week 2.
On this page
Five broken programs, one for each idea of this week. Two of them do not compile. The other three compile, and then crash or print a wrong answer, because Go’s compiler catches less than you might hope after this week. Those are the ones to learn to see.
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 you start Week 2.
1. A price from a form field
The number of nights comes from a form as text. The program compiles and runs:
package main
import (
"fmt"
"strconv"
)
const nightlyCents = 12950
func main() {
input := "3 "
nights, _ := strconv.Atoi(input)
totalCents := nights * nightlyCents
fmt.Println("total in cents:", totalCents)
}
total in cents: 0Show the solution
One sentence: "3 " has a trailing space, so Atoi failed and returned 0, and the _ threw away the error that said so: the guest is charged nothing.
The fix: take the error and check it (the errors lesson). Whether to also trim the space is a product decision; failing loudly is not optional.
package main
import (
"fmt"
"os"
"strconv"
)
const nightlyCents = 12950
func main() {
input := "3 "
nights, err := strconv.Atoi(input)
if err != nil {
fmt.Fprintln(os.Stderr, "invalid number of nights:", err)
os.Exit(1)
}
totalCents := nights * nightlyCents
fmt.Println("total in cents:", totalCents)
}
invalid number of nights: strconv.Atoi: parsing "3 ": invalid syntax
exit status 12. Collecting booking IDs
package main
import "fmt"
func main() {
nights := map[int]int{1042: 3, 1043: 0, 1051: 5}
var empty []int
for id, n := range nights {
if n == 0 {
append(empty, id)
}
}
fmt.Println("bookings with no nights:", empty)
}
# hello
./main.go:11:4: append(empty, id) (value of type []int) is not usedShow the solution
One sentence: append does not change the slice you give it; it returns a new one, and here the result was thrown away.
The fix: assign it back, always: empty = append(empty, id) (the slices lesson).
package main
import "fmt"
func main() {
nights := map[int]int{1042: 3, 1043: 0, 1051: 5}
var empty []int
for id, n := range nights {
if n == 0 {
empty = append(empty, id)
}
}
fmt.Println("bookings with no nights:", empty)
}
bookings with no nights: [1043]3. A report with a map inside
This one compiles, and go vet and staticcheck are both quiet:
package main
import "fmt"
type Report struct {
Title string
Counts map[string]int
}
func main() {
report := Report{Title: "levels"}
for _, level := range []string{"INFO", "ERROR", "INFO"} {
report.Counts[level]++
}
fmt.Println(report.Title, report.Counts)
}
panic: assignment to entry in nil map
goroutine 1 [running]:
main.main()
/tmp/go-playbook/hello/main.go:14 +0x7d
exit status 2Show the solution
One sentence: the struct literal left Counts out, so it was the zero value of a map, nil, and writing to a nil map panics.
The fix: a function that builds a ready-to-use Report, so no caller can forget the map. It is Go’s answer to a constructor: a plain function, by convention named new….
package main
import "fmt"
type Report struct {
Title string
Counts map[string]int
}
func newReport(title string) Report {
return Report{Title: title, Counts: map[string]int{}}
}
func main() {
report := newReport("levels")
for _, level := range []string{"INFO", "ERROR", "INFO"} {
report.Counts[level]++
}
fmt.Println(report.Title, report.Counts)
}
levels map[ERROR:1 INFO:2]4. Applying a discount
Every booking of 7 nights or more gets 10% off. It compiles, runs, and is wrong:
package main
import "fmt"
type Booking struct {
Guest string
Nights int
TotalCents int
}
func main() {
bookings := []Booking{
{Guest: "Astrid", Nights: 3, TotalCents: 38850},
{Guest: "Bjorn", Nights: 7, TotalCents: 90650},
}
for _, b := range bookings {
if b.Nights >= 7 {
b.TotalCents = b.TotalCents * 90 / 100
}
}
for _, b := range bookings {
fmt.Printf("%s: %d\n", b.Guest, b.TotalCents)
}
}
Astrid: 38850
Bjorn: 90650Show the solution
One sentence: range handed out a copy of each booking, so the discount was applied to the copy and thrown away at the end of each round.
The fix: loop over the indexes and write through bookings[i] (the structs lesson).
package main
import "fmt"
type Booking struct {
Guest string
Nights int
TotalCents int
}
func main() {
bookings := []Booking{
{Guest: "Astrid", Nights: 3, TotalCents: 38850},
{Guest: "Bjorn", Nights: 7, TotalCents: 90650},
}
for i := range bookings {
if bookings[i].Nights >= 7 {
bookings[i].TotalCents = bookings[i].TotalCents * 90 / 100
}
}
for _, b := range bookings {
fmt.Printf("%s: %d\n", b.Guest, b.TotalCents)
}
}
Astrid: 38850
Bjorn: 815855. The average rating
package main
import "fmt"
func main() {
ratings := []float64{5, 4, 4, 5, 4}
sum := 0.0
for _, r := range ratings {
sum += r
}
fmt.Printf("average: %.1f\n", sum/len(ratings))
}
# hello
./main.go:13:32: invalid operation: sum / len(ratings) (mismatched types float64 and int)Show the solution
One sentence: len returns an int, sum is a float64, and Go never converts between them on its own.
The fix: convert on purpose (the variables lesson). Converting sum to int instead would compile too, and print 4 instead of 4.4: always convert towards the type that keeps the information. An empty slice would divide by zero, which for floats gives NaN, not a panic; check len(ratings) == 0 first when the data comes from outside.
package main
import "fmt"
func main() {
ratings := []float64{5, 4, 4, 5, 4}
sum := 0.0
for _, r := range ratings {
sum += r
}
fmt.Printf("average: %.1f\n", sum/float64(len(ratings)))
}
average: 4.4The logstat exit check
Before Week 2, your logstat from the build day must pass every line of this table. Week 2 builds on it.
| Check | How |
|---|---|
| Stack-trace lines are never counted as entries | The “other lines” number is not zero on a log with exceptions. |
| A cut-off entry is reported on stderr with its line number | Truncate a line of a copy of your log by hand. |
| No path: usage message, exit code 2 | go build && ./logstat; echo $? |
| Missing file: clear message, exit code 1 | ./logstat nope.log; echo $? |
| A 1 MB line is counted, not fatal | Add one to a copy of your log. |
No error thrown away with _ | Search the file. Each _ left needs a reason you can say. |
go vet ./... and staticcheck ./... are silent, and gofmt -l . prints nothing | Run all three. |
| On GitHub, with a README | One paragraph and one usage line is enough. |
What PHP would have done
The same five mistakes in PHP:
| Mistake | PHP | Go |
|---|---|---|
| 1. A number that is not a number | (int) "3 " is 3, but (int) "three" is 0: no error either way | An error you must not throw away |
| 2. Adding to a list | $ids[] = $id changes the array in place | append returns the new slice; ignoring it is a compile error |
| 3. A collection that was never created | $counts[$level]++ on null makes an array, with a warning | A nil map panics on the first write |
| 4. Changing rows in a loop | Arrays of arrays need &$b; objects change in place | A struct in a slice is a value: change it through the index |
| 5. Dividing a float by a count | Converts silently | Compile error until you convert on purpose |
Go catches two of the five at compile time and staticcheck catches one more in its simplest form (the nil map in the slices lesson). The rest are the habits this week is about: check every error, assign every append, create every map, and change slices through their index.
Remember
- The compiler catches less than it seems: a quiet build does not mean a right answer. Check errors, assign appends, create maps, change through indexes.
Week 2 starts with pointers and methods, then gives logstat real flags, wrapped errors, its own package and tests.