Skip to content

Checkpoint: Test a Stream Summary

The Course
•
24 min study
Exercise

Your turn

Write summarize, which takes an io.Reader and an io.Writer. It counts the nonblank lines, checks scanner.Err(), and then writes exactly one line, Tasks: followed by the count. Check it with a strings.Reader and a strings.Builder. For the input "Read\n\nDraft", two titles separated by a blank line, the captured text must be exactly "Tasks: 2\n", with its newline. panic if it differs, and otherwise print what was captured, so the program's output is:

Text
Tasks: 2
Your working space Go
package main

func main() {
	// Build your solution here.
}
Hint 1: the idea

Test both the input loop and the writer through a single function call.

Hint 2: a first step

Count only when strings.TrimSpace of the scanned line is nonempty.

Worked solution
Run the solution Go
package main

import (
	"bufio"
	"fmt"
	"io"
	"strings"
)

func summarize(r io.Reader, w io.Writer) error {
	scanner := bufio.NewScanner(r)
	count := 0
	for scanner.Scan() {
		if strings.TrimSpace(scanner.Text()) != "" {
			count++
		}
	}
	if err := scanner.Err(); err != nil {
		return err
	}
	_, err := fmt.Fprintln(w, "Tasks:", count)
	return err
}

func main() {
	var out strings.Builder
	if err := summarize(strings.NewReader("Read\n\nDraft"), &out); err != nil {
		panic(err)
	}
	if out.String() != "Tasks: 2\n" {
		panic(out.String())
	}
	fmt.Print(out.String())
}
Text
Tasks: 2

This is the shape of the queue's run: read commands, write results and return any input or output error to the caller.

Was this article helpful?

Your response is saved on this device.