liveBook · Manning

SplitFunc

As explained in Go in Action, Second Edition

SplitFunc is the function type used by bufio.Scanner to define how input is divided into tokens.

SplitFunc is a Go function type that lets bufio.Scanner decide how input becomes tokens. A Scanner normally returns newline-delimited lines, but assigning a compatible function changes that behavior without replacing the Scanner. section 2.8.4 section 2.8.1

Listing 2.43 Excerpt from go doc bufio SplitFunc
type SplitFunc func(data []byte, atEOF bool)
	(advance int, token []byte, err error)

	SplitFunc is the signature of the split function used to tokenize the
    input. The arguments are an initial substring of the remaining
    unprocessed data and a flag, atEOF, that reports whether the Reader has
    no more data to give. The return values are the number of bytes to
    advance the input and the next token to return to the user, if any, plus
    an error, if any.

Use the documented signature to understand the scanner contract: inspect remaining bytes, account for end-of-input, then return an advance count, token, and possible error. section 2.8.4

A SplitFunc-based design provides:

  • Function-type flexibility: any function with the required inputs and outputs can be assigned to the scanner. section 2.8.4
  • Predefined choices for lines, bytes, UTF-8 runes, and space-delimited words, including bufio.ScanWords. section 2.8.1 section 2.8.4
  • A clean alternative to splitting each scanned line manually with strings.Fields when counting words. section 2.8.4 section 2.8.1

Count words with ScanWords

scanner := bufio.NewScanner(file) scanner.Split(bufio.ScanWords) var wordCount int for scanner.Scan() { wordCount++ } section 2.8.4

How Go in Action, Second Edition covers it

How deep it goes
Defines the function signature and substitution model, but defers broader function-type details and scanner implementation behavior.
Examples
Demonstrates replacing line scanning with ScanWords to count space-separated words.
What it assumes
Assumes familiarity with bufio.Scanner and function signatures while introducing function values as interchangeable behavior.
What you can do after
Apply it via bufio.Scanner to select predefined tokenization or provide a compatible custom splitter.
How it connects
Connects function types with bufio.Scanner, ScanWords, tokenization, and custom split functions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.