Scan tokens with explicit limits
Scan tokens with explicit limits
bufio.Scanner splits a stream into tokens. By default it scans lines without line endings. Split(bufio.ScanWords) selects whitespace-separated words. Scan returns false at completion or failure. Always check Err after the loop and configure Buffer before scanning.
package main
import ( "bufio" "fmt" "strings")
func main() { s := bufio.NewScanner(strings.NewReader("one two\nthree")) s.Split(bufio.ScanWords) s.Buffer(make([]byte, 0, 16), 64) for s.Scan() { fmt.Println(s.Text()) } fmt.Println(s.Err() == nil)}ScanWords uses Unicode whitespace. Text returns the latest token as a string; Bytes returns a slice that may be overwritten by the next Scan. Copy that slice to retain it. Configure Split and Buffer before scanning starts.
Expected output:
onetwothreetrueReject oversized tokens
package main
import ( "bufio" "fmt" "strings")
func main() { s := bufio.NewScanner(strings.NewReader(strings.Repeat("x", 32))) s.Buffer(make([]byte, 0, 4), 8) fmt.Println(s.Scan()) fmt.Println(s.Err() != nil)}The default maximum buffer is MaxScanTokenSize (64 KiB in Go 1.23.2). The actual token limit may be smaller because delimiters need space. Buffer capacity also affects the effective bound. Here capacity four and maximum eight reject a 32-byte token. Scanner stops on a too-long token. Use a Reader with an explicit length policy for more control. Token limits do not bound total input or token count.
Expected output:
falsetrueTry it locally
Count words in "a bb ccc" with ScanWords, initial capacity 8 and maximum 32. Check Err and print the count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O contracts 07: Scan tokens with explicit limits
Check the lesson objective before moving on.
When should Scanner.Buffer be called?
What should you check when Scan returns false?