Come back to this page twice: the first two challenges after about a week, the last two after about a month.
What you can recall after a gap, without looking, is a better guide to what you have learned than what you could do the day you read it. The effort of pulling an idea back out of memory is what makes it stick. The week challenges cover returning a separate slice and keeping an error's cause. The month challenges cover the ideas the task queue is built on: an interface whose methods change their receiver, and a sorted report written through an io.Writer and checked from code.
How to use this page
Set a timer for about ten minutes per exercise and work without scrolling back through the course. If you get stuck, take the first hint only, then try again before opening the second. A different solution is fine if it handles the same cases.
After a week
Protect the source
Your turn
Write firstTwo to return a copy of at most the first two titles. Change the returned slice and check that the original does not change. Also check a one-title input.
package main
func main() {
// Build a separate result and check short input.
}Hint 1: the idea
Limit the prefix length to what the caller supplied.
Hint 2: a first step
Compute the smaller of 2 and len(titles) before slicing; the built-in min does this.
Worked solution
package main
import (
"fmt"
)
func firstTwo(titles []string) []string {
n := min(2, len(titles))
result := make([]string, n)
copy(result, titles[:n])
return result
}
func main() {
source := []string{"Read", "Draft", "Review"}
result := firstTwo(source)
result[0] = "Edited"
fmt.Println(source)
fmt.Println(firstTwo([]string{"Read"}))
}[Read Draft Review]
[Read]The result can be edited because its backing array is separate.
Preserve a cause
Your turn
Define a shared missing-task error, wrap it with the ID 9 and print whether errors.Is still recognizes the cause. Then replace the wrapping verb in the program and verify the boolean changes.
package main
func main() {
// Define a sentinel and wrap it with context.
}Hint 1: the idea
Error text can stay the same even when error identity changes.
Hint 2: a first step
Use fmt.Errorf with a verb that keeps an error as its cause.
Worked solution
package main
import (
"errors"
"fmt"
)
var errMissing = errors.New("not found")
func main() {
err := fmt.Errorf("task %d: %w", 9, errMissing)
fmt.Println(err)
fmt.Println(errors.Is(err, errMissing))
}task 9: not found
true%w makes the original error discoverable by errors.Is. With %v the text is identical but the boolean is false.
After a month
Count through an interface
Your turn
Define an interface Counter with two methods, Add(n int) and Total() int, and a struct Tally that implements it by keeping a running sum. Write addAll(c Counter, values []int), which adds every value. Call it on one tally with 25, 40 and 15, print the total, then call it again with no values and print the total once more. The output should be:
80
80package main
func main() {
// Define Counter and Tally, then addAll.
}Hint 1: the idea
Which of the two methods changes its receiver? The answer decides the receiver type, and that decides whether Tally or *Tally satisfies Counter.
Hint 2: a first step
Write Tally and its two methods first and call them directly in main, without the interface. When the total is right, add Counter and addAll and pass the tally to it.
Worked solution
package main
import "fmt"
type Counter interface {
Add(n int)
Total() int
}
type Tally struct {
sum int
}
func (t *Tally) Add(n int) {
t.sum += n
}
func (t *Tally) Total() int {
return t.sum
}
func addAll(c Counter, values []int) {
for _, v := range values {
c.Add(v)
}
}
func main() {
var minutes Tally
addAll(&minutes, []int{25, 40, 15})
fmt.Println(minutes.Total())
addAll(&minutes, nil)
fmt.Println(minutes.Total())
}80
80Add must change the caller's tally, so it has a pointer receiver, and Total uses one too so both methods belong to the same type. Only *Tally has both methods, so addAll(&minutes, ...) compiles and addAll(minutes, ...) does not. With a value receiver on Add, the program would compile and print 0: each call would change a copy.
A sorted report you can check
Your turn
Write writeReport(w io.Writer, minutes map[string]int) error, which writes one title: minutes line per entry in title order and returns the first write error. In main, write the report for Review 15, Draft 30 and Read 20 into a strings.Builder five times and compare it each time with the exact text you expect. Also check that an empty map writes nothing. When every check passes, print:
report checks passedpackage main
func main() {
// Write the report into a builder and compare it.
}Hint 1: the idea
A map's order changes from run to run, so the report needs its own order, and the caller, not the function, chooses where the text goes. Repeating the check is what would catch a report that is only sometimes in order.
Hint 2: a first step
Collect the titles into a slice, sort it, and print the lines with fmt.Println first to see the order. Then switch to fmt.Fprintf on the writer and capture the result in a builder.
Worked solution
package main
import (
"fmt"
"io"
"slices"
"strings"
)
func writeReport(w io.Writer, minutes map[string]int) error {
titles := make([]string, 0, len(minutes))
for title := range minutes {
titles = append(titles, title)
}
slices.Sort(titles)
for _, title := range titles {
if _, err := fmt.Fprintf(w, "%s: %d\n", title, minutes[title]); err != nil {
return err
}
}
return nil
}
func main() {
minutes := map[string]int{"Review": 15, "Draft": 30, "Read": 20}
want := "Draft: 30\nRead: 20\nReview: 15\n"
for i := 0; i < 5; i++ {
var out strings.Builder
if err := writeReport(&out, minutes); err != nil {
fmt.Println(err)
return
}
if out.String() != want {
fmt.Printf("got %q\n", out.String())
return
}
}
var empty strings.Builder
if err := writeReport(&empty, map[string]int{}); err != nil || empty.Len() != 0 {
fmt.Println("empty map should write nothing")
return
}
fmt.Println("report checks passed")
}report checks passedRanging over the map directly would produce the right lines in a different order on some runs, and the repeated comparison would catch it. writeReport never prints: it writes to whatever the caller passes, so main can compare the exact text, line endings included, and the queue's main can pass os.Stdout. The function returns the write error rather than ignoring it, as Day 6 checked.
If you got stuck
Getting stuck here tells you which lesson to revisit:
- Copying a slice, or a result that changes the source: Day 2, See When Slices Share Storage and Return a Separate Slice.
%w,%vanderrors.Is: Day 5, Recognize a Known Error and Add Context and Keep the Cause.- Pointer receivers, or which type implements an interface: Day 1, Change the Original Record, and Day 4, Know Which Type Implements the Interface.
- Sorted keys: Day 3, Make a Report Deterministic.
io.Writerand checking output from code: Day 4, Write Through io.Writer, and Day 6, Verify a Full Transcript.
Reread the lesson, close it, and try the exercise again from a blank editor. Then come back once more after another few days. When all four feel routine, you are ready for the advanced course.
Completion is saved in this browser only. It does not measure mastery.