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:
Tasks: 2package 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
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())
}Tasks: 2This is the shape of the queue's run: read commands, write results and return any input or output error to the caller.
Completion is saved in this browser only. It does not measure mastery.