Skip to content

Inject a Reader

The Course
•
25 min study

A function that reads os.Stdin itself can only be tried by typing at it. To check it from code, with the same input every time, you would have to change the function. io.Reader solves this the way io.Writer did for output: the function asks for "something that supplies bytes", and the caller decides what that is.

io.Reader is another one-method interface, Read(p []byte) (n int, err error). os.Stdin satisfies it, and so does strings.NewReader("..."), which supplies the bytes of a string. Pass a reader into the function instead of reading os.Stdin inside it, and wrap it in a bufio.Scanner as before. A scanner still returns a final nonempty line that has no newline.

Predict and run

How many lines does countLines find?

Predict, then run Go
package main

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

func countLines(r io.Reader) (int, error) {
	scanner := bufio.NewScanner(r)
	count := 0
	for scanner.Scan() {
		count++
	}
	return count, scanner.Err()
}

func main() {
	count, err := countLines(strings.NewReader("first\nsecond"))
	if err != nil {
		panic(err)
	}
	fmt.Println(count)
}
Check your prediction
Text
2

Try the empty string, then a single newline. Compare the counts.

Trace the edge cases

Run countLines on a few inputs whose answers are easy to get wrong:

Edge cases in one run Go
package main

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

func countLines(r io.Reader) (int, error) {
	scanner := bufio.NewScanner(r)
	count := 0
	for scanner.Scan() {
		count++
	}
	return count, scanner.Err()
}

func main() {
	for _, text := range []string{"", "\n", "a\n", "a\n\nb", "a\nb\n"} {
		count, err := countLines(strings.NewReader(text))
		if err != nil {
			panic(err)
		}
		fmt.Printf("%q -> %d\n", text, count)
	}
}
Text
"" -> 0
"\n" -> 1
"a\n" -> 1
"a\n\nb" -> 3
"a\nb\n" -> 2

A newline ends a line, it doesn't start a new one, so "a\n" is one line and "\n" is one empty line. The blank line in the middle of "a\n\nb" counts, and so does the final b with no newline after it. These are exactly the cases that are tedious to type at a terminal and trivial with strings.NewReader.

scanner.Err() matters even though these inputs never fail. A real reader can fail halfway, a file on a disconnected drive for example, and Scan then returns false exactly as it does at the end of the input. Only Err tells the two apart.

Practice

Exercise

Your turn

Write longest(r io.Reader) (string, error), which returns the longest line after trimming spaces, ignoring blank lines. When there are no nonblank lines, it returns the empty string. Check it with the starter's three inputs. The output should be:

Text
"Review notes"
""
"Draft"
Your working space Go
package main

import (
	"fmt"
)

func main() {
	inputs := []string{"Read\n  Review notes  \n\nDraft", "\n \n", "Draft"}
	fmt.Println(len(inputs))
}
Hint 1: the idea

The function never knows where its input came from: it scans whatever reader it is given and keeps the best line so far, an accumulator like the beginner's largest value. main makes a fresh strings.Reader for each input.

Hint 2: a first step

Write the loop so it returns the last trimmed line, and print the results with %q. Then keep a line only when it is longer than the best one so far.

Worked solution
Run the solution Go
package main

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

func longest(r io.Reader) (string, error) {
	scanner := bufio.NewScanner(r)
	best := ""
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if len(line) > len(best) {
			best = line
		}
	}
	if err := scanner.Err(); err != nil {
		return "", err
	}
	return best, nil
}

func main() {
	inputs := []string{"Read\n  Review notes  \n\nDraft", "\n \n", "Draft"}
	for _, text := range inputs {
		line, err := longest(strings.NewReader(text))
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Printf("%q\n", line)
	}
}
Text
"Review notes"
""
"Draft"

Blank lines need no special case: trimmed, they have length 0 and can never beat best. Starting best at "" makes the all-blank input return the empty string. The spaces around Review notes don't count towards its length, because the line is trimmed before it is compared.

Was this article helpful?

Your response is saved on this device.