Scanner ScanWords Tokenizes Input
bufio.ScanWords streams whitespace-separated tokens from any reader, so word counting works incrementally without loading whole input.
Code
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
input := "retry 3 times with\tbackoff"
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Split(bufio.ScanWords)
tokens := 0
// ScanWords tokenizes each whitespace run into one word
for scanner.Scan() {
tokens++
fmt.Printf("token %d: %q\n", tokens, scanner.Text())
}
if err := scanner.Err(); err != nil {
panic(err)
}
fmt.Println("total words:", tokens)
}How it works
Scanner ScanWords Tokenizes Input comes down to the function main.
A single loop drives the file — for scanner.Scan(). Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.
What to watch for
- Nothing external — every call lands on the language’s built-in API surface.
- Failures abort via
panic(err)— nothing is returned for the caller to check, and nothing in the snippet recovers.
Using it
Signature: func main()
The demo output is labeled (token, total words:), so every line in the printed output names the step that produced it.
The key statements, annotated
if err := scanner.Err(); err != nil {
panic(err)
}
Interactive Tools for This Topic
LLM Token & Cost EstimatorEstimate BPE-approximate LLM token counts across English, CJK text, and source code and compare request and batch costs across pricing tiers.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text Tokenizer LiteSplit text into word, number, punctuation, and whitespace tokens, with counts per category and the list of unique words.
FAQ
- How should callers handle failures?
- By terminating the run: `panic(err)` fires at each of the 1 check, so callers see failures only as a stopped program.
- What does Scanner ScanWords Tokenizes Input print when run?
- Execute the whole file; each printed line is prefixed with a label like `token`, `total words:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.