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?
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
2Try 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:
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)
}
}"" -> 0
"\n" -> 1
"a\n" -> 1
"a\n\nb" -> 3
"a\nb\n" -> 2A 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
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:
"Review notes"
""
"Draft"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
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)
}
}"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.
Completion is saved in this browser only. It does not measure mastery.