Reading lines and words with bufio.Scanner
- Version
- 1.27
- Since
- 1.1
- Review
- Draft
Summary#
A bufio.Scanner reads input one token at a time. Tokens are lines by default, without the line ending. Split selects another unit, and Err reports a failure after the loop.
Syntax#
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
}
err := scanner.Err()
Example#
package main
import (
"bufio"
"errors"
"fmt"
"strings"
)
func main() {
input := "red green\r\nblue red\n"
lines := bufio.NewScanner(strings.NewReader(input))
for number := 1; lines.Scan(); number++ {
fmt.Printf("%d: %q\n", number, lines.Text())
}
fmt.Println("line error:", lines.Err())
words := bufio.NewScanner(strings.NewReader(input))
words.Split(bufio.ScanWords) // set before the first Scan
counts := map[string]int{}
for words.Scan() {
counts[words.Text()]++
}
fmt.Println(counts, words.Err())
narrow := bufio.NewScanner(strings.NewReader("abcdefghij\n"))
narrow.Buffer(make([]byte, 4), 8) // at most 8 bytes buffered
fmt.Println(narrow.Scan(), errors.Is(narrow.Err(), bufio.ErrTooLong))
}
Expected output#
1: "red green"
2: "blue red"
line error: <nil>
map[blue:1 green:1 red:2] <nil>
false true
Common mistakes#
A false Scan result can mean end of input or an error, so always check Err. The default buffer limit is 64 KiB (bufio.MaxScanTokenSize). A token may need extra space for a delimiter such as a newline. Call Buffer before the first Scan, or use a bufio.Reader for longer lines. The slice from Bytes may be overwritten by the next scan, so copy it to keep it.
Version applicability#
Scanner and the standard split functions arrived in Go 1.1. Buffer requires Go 1.6 or later. The example relies on sorted map formatting from Go 1.12 and errors.Is from Go 1.13, so it requires Go 1.13 or later.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0