Scanner ScanWords Tokenizes Input

bufio.ScanWords streams whitespace-separated tokens from any reader, so word counting works incrementally without loading whole input.

GoData Integrity

Code

gosnippet
24 lines
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

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:`.