Skip to content

Run the Reading Log

The Course
•
18 min study

Today you put the week together. The reading log is a complete, if small, Go program: it reads reading sessions from standard input, checks each one, and prints a report of the sessions it accepted. Nothing in it is new. Every line uses something from Days 1 to 6, and the interesting part is seeing how those pieces fit into one program that a person could actually use.

The input format is one title and duration per line, separated by a comma. Titles cannot contain commas. The program accepts 1–240 whole minutes, ignores blank lines, and prints the accepted sessions in input order. It reports invalid records with their original line numbers.

Predict and run

How many sessions will the summary count? How many minutes? Switch between the two source tabs after your prediction.

Run the reading log 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
Check your prediction
Text
Line 2: use 1–240 whole minutes
Reading log
Poems: 25 min
Short stories: 35 min
Sessions: 2 | Minutes: 60

Add a valid record after the last line. Then try a final line without a newline. Explain why the invalid row never reaches the total.

How the program is organized

The program is split across two files, and the split is deliberate:

  • main.go talks to the outside world. It creates the scanner, counts line numbers, skips blank lines, prints a message for each rejected line, and prints the final report.
  • log.go holds the rules. parseSession turns one line into a Session or an error, and totalMinutes adds up a slice of sessions. Neither function reads input or prints anything.

Keeping the rules away from input and output is what makes them easy to check. parseSession can be called with any string you like, without typing anything into a stdin box, and its result can be compared with an expected value. You will do exactly that in the third lesson today.

The rules in one place

Every rejected line gets exactly one message, chosen by the first rule it breaks:

  • No comma: use title,minutes
  • A blank title after trimming: title is required
  • Minutes that are not a whole number, or are outside 1 to 240: use 1–240 whole minutes

Each message tells the person what to type instead, rather than only that something went wrong. Combined with the line number, that is usually enough to fix a mistake without reading any code.

Why the report comes last

The program prints rejected lines as it meets them, but it holds the accepted sessions in a slice and prints the report only once all input has been read. That order is not an accident. The total and the session count depend on every line, so they cannot be known until the end. Printing problems first also puts them where a person reads first, above the report they affect.

Two kinds of failure

A bad line is expected, so the program reports it and keeps going. A failure to read input at all is different: scanner.Err() returns an error, and the program writes it to standard error with fmt.Fprintln(os.Stderr, ...) and stops without printing a report. A partial report from half-read input would be misleading, so no report is the safer choice.

What to look for as you explore

Open both tabs in the editor. In main.go, find the two continue statements and say which situation each one handles. In log.go, find where trimming happens and check that it happens before each test that depends on it. Then change the sample input to break each rule in turn, and predict the exact output before every run.

Was this article helpful?

Your response is saved on this device.