bufio.NewScanner, Scanner.Scan, Scanner.Text, Scanner.Err, Scanner.Buffer, bufio.ErrTooLong
func NewScanner(r io.Reader) *Scanner
func (s *Scanner) Scan() bool
func (s *Scanner) Text() string
func (s *Scanner) Err() error
func (s *Scanner) Buffer(buf []byte, max int)
const MaxScanTokenSize = 64 * 1024
var ErrTooLong = errors.New("bufio.Scanner: token too long")Scan lines, check Err at EOF, and detect a token that exceeds the buffer limit.
| Parameter | Description |
|---|---|
r | The underlying io.Reader. NewScanner does not close it. |
buf / max | Buffer sets the initial backing array and the maximum token size. Official documentation says the maximum token size must be less than the larger of max and cap(buf). Buffer panics if it is called after scanning has started. |
Returns: Scan returns whether a token was read. Text returns that token without the trailing newline. Err returns nil at a clean EOF, or ErrTooLong when a token is too large.
Errors
ErrTooLong— The token is larger than the Scanner buffer allows. Compare with errors.Is. The default limit is MaxScanTokenSize, 64 KiB.
- The examples print errors.Is and sc.Err() == nil rather than the ErrTooLong string.
package main
import (
"bufio"
"errors"
"fmt"
"strings"
)
func main() {
sc := bufio.NewScanner(strings.NewReader("one\ntwo\nthree"))
var lines []string
for sc.Scan() {
lines = append(lines, sc.Text())
}
fmt.Printf("%q %v\n", lines, sc.Err())
sc2 := bufio.NewScanner(strings.NewReader("abcdefghij\n"))
sc2.Buffer(make([]byte, 0, 4), 4)
fmt.Println(sc2.Scan(), errors.Is(sc2.Err(), bufio.ErrTooLong))
}Expected output
["one" "two" "three"] <nil>
false trueRelated: io