Understand the contract
bufio.Scanner splits input into tokens, using lines by default. Call Scan repeatedly, consume Text for each token and check Err after the loop. A false Scan result can mean normal end of input or a scanning failure; checking Err distinguishes those outcomes.
Scanner has a token-size limit. Buffer lets you supply initial storage and a maximum before scanning starts. The example allows lines up to the configured bound rather than treating input size as unlimited. For inputs requiring larger or custom streaming behavior, bufio.Reader offers different tradeoffs.
Work through the example
The example trims each line and skips blank results, printing go and tests. TrimSpace is an application decision: source code, fixed-width records or user messages may need to preserve whitespace. Scanner.Text returns a string; Scanner.Bytes returns a buffer that later scanning can overwrite.
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
scanner := bufio.NewScanner(strings.NewReader("go\n\n tests \n"))
scanner.Buffer(make([]byte, 1024), 64*1024)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line != "" { fmt.Println(line) }
}
if err := scanner.Err(); err != nil { fmt.Println("scan:", err) }
}Watch this boundary
Ignoring scanner.Err can silently accept a truncated import when a line exceeds the limit. Choose whether failure should discard all processed records or report a partial result. For an all-or-nothing import, avoid committing records until validation has established that the complete input is acceptable.
Practice with a changed input
Create a line larger than the configured maximum and verify that Err is reported. Then preserve blank lines and compare the output with the filtering version.
Lesson 34 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services