Skip to content

Add a Reading Goal and Download the Project

The Course
•
20 min study

The last step of a project is often the most satisfying: change it to do something new, then run it on your own computer. The extension here is small on purpose. It adds a line to the report, and doing it well means deciding where the new code belongs, keeping the existing output unchanged, and testing the boundary of the new rule.

Plan the change

The report should end with Goal met when the accepted sessions add up to 60 minutes or more, and Keep reading otherwise. Before writing anything, answer three questions:

  1. Which minutes count? Only accepted sessions. Rejected lines never reach the slice, so the existing totalMinutes(sessions) already gives the right number.
  2. Where does the line go? After the summary line in main.go, because it is part of the report. The existing lines must stay exactly as they are.
  3. How will you test the boundary? The sample totals exactly 60, so it should meet the goal. Lowering one session by a single minute should flip the result. Testing both sides of the cutoff is the same habit as on Day 2.
Name the rule if it grows

A single if in main.go is fine for one goal. If the goal becomes configurable or gets more rules, move it into log.go as a function such as goalMet(total int) bool, and add a row for it to the checks. That keeps rules where the checks can reach them.

Exercise

Report a 60-minute goal

Add a line after the summary in main.go. Print Goal met for 60 or more accepted minutes and Keep reading otherwise. Run it on the sample, then reduce its 35-minute session to 34.

Your working space Go
package main import ( "bufio" "fmt" "os" "strings" ) func main() { scanner := bufio.NewScanner(os.Stdin) var sessions []Session lineNumber := 0 for scanner.Scan() { lineNumber++ line := scanner.Text() if strings.TrimSpace(line) == "" { continue } session, err := parseSession(line) if err != nil { fmt.Printf("Line %d: %s\n", lineNumber, err) continue } sessions = append(sessions, session) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "Input error:", err) return } fmt.Println("Reading log") for _, session := range sessions { fmt.Printf("%s: %d min\n", session.Title, session.Minutes) } fmt.Printf("Sessions: %d | Minutes: %d\n", len(sessions), totalMinutes(sessions)) } package main import ( "errors" "strconv" "strings" ) type Session struct { Title string Minutes int } func parseSession(line string) (Session, error) { title, rawMinutes, ok := strings.Cut(line, ",") if !ok { return Session{}, errors.New("use title,minutes") } title = strings.TrimSpace(title) if title == "" { return Session{}, errors.New("title is required") } minutes, err := strconv.Atoi(strings.TrimSpace(rawMinutes)) if err != nil || minutes < 1 || minutes > 240 { return Session{}, errors.New("use 1–240 whole minutes") } return Session{Title: title, Minutes: minutes}, nil } func totalMinutes(sessions []Session) int { total := 0 for _, session := range sessions { total += session.Minutes } return total } Poems,25 Essays,0 Short stories,35
Hint 1: the idea

Use only durations from accepted sessions.

Hint 2: a first step

Compare the value returned by totalMinutes with 60.

Worked solution

Insert this after the summary line, inside main:

Go
if totalMinutes(sessions) >= 60 {
	fmt.Println("Goal met")
} else {
	fmt.Println("Keep reading")
}

The sample meets the goal exactly. Reducing the last duration to 34 makes the accepted total 59.

Try it locally (optional)

Everything in this course runs in the browser, so this part is optional. If you have never used a terminal before, follow these steps in order. Each one says what you should see.

  1. Install Go. Download the installer for your system from the official page at go.dev and run it. It includes the compiler, the formatter and the test runner, so there is nothing else to install.
  2. Open a terminal. On macOS, open the Terminal app from Applications, then Utilities. On Windows, open the Start menu and type cmd to open Command Prompt. On Linux, open your Terminal app. If the terminal was already open before you installed Go, close it and open a new one.
  3. Check Go. Type go version and press Enter. You should see a line such as go version go1.24.0 followed by your system. A version of 1.24 or newer is fine. command not found or 'go' is not recognized means the terminal was opened before the install finished: open a new one.
  4. Download and extract the project. Download the original reading log. On macOS, double-click the zip. On Windows, right-click it and choose Extract All. You get a folder with go.mod, the .go files and sample.txt.
  5. Move into the folder. Type cd, a space, then drag the extracted folder onto the terminal window, which types its path for you, and press Enter. Then type ls (macOS, Linux) or dir (Windows) and check that go.mod is in the list.
  6. Run it. Type the commands below, one at a time.
Shell
go run . < sample.txt
go test .

The first prints the same report you saw in the browser. The second prints a line starting with ok.

Windows PowerShell does not accept <

If your Windows terminal says PS at the start of the prompt, it is PowerShell, not Command Prompt, and go run . < sample.txt fails with an error saying the < operator is reserved for future use. Either type cmd and press Enter to switch to Command Prompt, or pipe the file in instead: Get-Content sample.txt | go run .

The zip includes the original sources, sample input and a native test file. Browser practice uses one main package with no module imports. The local Go tool also runs files ending in _test.go through its testing package.

The project folder contains a file called go.mod. It marks the folder as a Go module, a unit of code with a name and a minimum Go version. Commands such as go run . and go test . use it to find the package; the . means "the package in this folder".

What the commands do

  • go run . < sample.txt compiles the package and runs it, with sample.txt connected to standard input. The output matches what you saw in the browser.
  • go run . on its own waits for you to type lines. Type a few sessions, then press Ctrl+D on macOS or Linux, or Ctrl+Z then Enter on Windows, to signal the end of input.
  • go test . runs log_test.go and prints ok when every check passes. Add -v to see each test by name.
  • gofmt -l . lists any file that is not formatted the standard way. An empty result means the code is formatted.
  • go vet . looks for suspicious code that compiles but is probably wrong, such as a Printf verb that does not match its argument.

Where to go next

Try your goal extension locally, and run it on input that reaches the goal and input that doesn't. log_test.go shows what Go's own tests look like, though this course doesn't teach the testing package; the intermediate course does. After that, the intermediate course builds a larger program, a task queue, and introduces methods, interfaces, wrapped errors and code that is split along clearer boundaries.

Was this article helpful?

Your response is saved on this device.