Come back to this page twice: the first two challenges after about a week, the last two after about a month.
Remembering something right after you learn it is easy, because it is still fresh. What you can recall a few days later, without looking, is a much better guide to what you have really learned. Coming back after a gap feels harder, and that effort is the point: each time you pull an idea back out of memory, it becomes easier to find the next time. The week challenges cover a loop with a condition and an error check on converted text. The month challenges cover the ideas the intermediate course builds on straight away: a slice of structs summed into a map, and a function that returns (int, error) with a table check that proves it.
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. When you finish, compare your solution with the worked one. A different solution is fine if it handles the same cases; the point is that you could build it on your own.
After a week
Count values
Before you start, recall the parts you need: a function that takes a []int and returns an int, a counter that starts at zero, a range loop, and an if that includes the cutoff value.
Your turn
Write a function that counts the sessions of at least 30 minutes in a slice. Call it for the slice 45, 30, 12 and 29, and for an empty slice. The output should be:
2
0package main
func main() {
// Write a function and call it for both inputs.
}Hint 1: the idea
A value exactly on the cutoff should be counted, so 30 counts and 29 does not.
Hint 2: a first step
Pass the slice into a function and use range.
Worked solution
package main
import (
"fmt"
)
func count(values []int) int {
result := 0
for _, v := range values {
if v >= 30 {
result++
}
}
return result
}
func main() {
fmt.Println(count([]int{45, 30, 12, 29}))
fmt.Println(count([]int{}))
}2
030 sits exactly on the cutoff and 29 just below it, so the pair checks the >=. The counter stays zero when there are no values.
Validate a number
This one combines three ideas from Day 5: trimming text, converting it with strconv.Atoi, and checking the error before the range. Say aloud what each of the three inputs should print before you write any code.
Your turn
Try converting " 20 ", "later" and "0" to integers. Print the accepted duration or Invalid. Reject zero too. The output should be:
20
Invalid
Invalidpackage main
func main() {
// Add a conversion loop.
}Hint 1: the idea
Handle bad text and out-of-range values before using a duration.
Hint 2: a first step
Trim each string and keep both results from strconv.Atoi.
Worked solution
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
for _, text := range []string{" 20 ", "later", "0"} {
n, err := strconv.Atoi(strings.TrimSpace(text))
if err != nil || n < 1 {
fmt.Println("Invalid")
continue
}
fmt.Println(n)
}
}20
Invalid
InvalidTrimming helps the first input; it cannot make the other inputs valid.
After a month
Total by title
This one uses Day 4: a struct type, a slice of records, and a map that combines records sharing a key. Recall why printing straight from a range over the map is not enough before you start.
Your turn
Declare an Activity struct with a Name and Minutes. Make a slice of four activities: Swim 30, Walk 20, Swim 25 and Walk 15. Total the minutes per name in a map, then print the totals with Walk first and Swim second, every time you run it. The output should be:
Walk: 35
Swim: 55package main
func main() {
// Declare the type above main, then build the totals here.
}Hint 1: the idea
A missing key reads as 0, so += on the map works for a name's first record too. Map order changes from run to run, so the print order has to come from something that keeps order.
Hint 2: a first step
Build the map and print it with fmt.Println(totals). You should see map[Swim:55 Walk:35]. Then range over a slice holding "Walk" and "Swim" to print the two lines.
Worked solution
package main
import (
"fmt"
)
type Activity struct {
Name string
Minutes int
}
func main() {
activities := []Activity{
{Name: "Swim", Minutes: 30},
{Name: "Walk", Minutes: 20},
{Name: "Swim", Minutes: 25},
{Name: "Walk", Minutes: 15},
}
totals := map[string]int{}
for _, a := range activities {
totals[a.Name] += a.Minutes
}
for _, name := range []string{"Walk", "Swim"} {
fmt.Printf("%s: %d\n", name, totals[name])
}
}Walk: 35
Swim: 55The slice of names fixes the order and the map supplies the numbers. Ranging over totals directly would print the same two lines, but not always in the same order.
Return an error and prove it
This one uses Day 6: a function with two results, fmt.Errorf, and a table of cases on and just outside each boundary.
Your turn
Write parseRating(text string) (int, error) for a star rating from 1 to 5. Text that is not a whole number, and numbers outside 1 to 5, return 0 and an error. Check it with a table of five rows: "1", "5", "0", "6" and "five". Each row says whether an error is expected. Use panic on a mismatch, and print this when every row passes:
5 checks passedpackage main
func main() {
// Write parseRating above main, then the table here.
}Hint 1: the idea
The function has two ways to fail and checks them in order: conversion first, then range. Each table row needs the input text, the expected number and whether an error is expected.
Hint 2: a first step
Write the table as a slice of an anonymous struct with three fields, and loop over it printing what parseRating returns for each row. Only then replace the printing with a comparison.
Worked solution
package main
import (
"fmt"
"strconv"
)
func parseRating(text string) (int, error) {
stars, err := strconv.Atoi(text)
if err != nil {
return 0, fmt.Errorf("%q is not a whole number", text)
}
if stars < 1 || stars > 5 {
return 0, fmt.Errorf("%d is outside 1 to 5 stars", stars)
}
return stars, nil
}
func main() {
cases := []struct {
text string
want int
wantErr bool
}{
{"1", 1, false}, {"5", 5, false}, {"0", 0, true}, {"6", 0, true}, {"five", 0, true},
}
for _, c := range cases {
got, err := parseRating(c.text)
if got != c.want || (err != nil) != c.wantErr {
panic(fmt.Sprintf("parseRating(%q) = %d, %v", c.text, got, err))
}
}
fmt.Printf("%d checks passed\n", len(cases))
}5 checks passedChange stars > 5 to stars >= 5 and run it: the "5" row panics. That is how you know the table really guards the upper bound.
If you got stuck
Getting stuck here is useful information, not a failure. It tells you which lesson to revisit:
- Loop boundaries or the cutoff: Day 2, Choose a Branch and Repeat with for.
- Passing a slice to a function, or
range: Day 3, Give a Calculation a Name and Visit a Slice with range. - Converting text and checking
err: Day 5, Check a Returned Error. - Trimming: Day 5, Split and Validate a Line.
- Structs, slices of records and map totals: Day 4.
- Returning an
errorand table checks: Day 6.
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 intermediate course.
Completion is saved in this browser only. It does not measure mastery.