Write A Custom bufio SplitFunc

Teach Scanner to split records on any delimiter by writing a SplitFunc with advance, token, and the three return cases every implementation needs.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"strings"
)

func main() {
	// 字段用 " | " 分隔:内置的按行、按词切不开,需要自定义 SplitFunc
	input := strings.NewReader("user=ada | action=login | ip=203.0.113.7")

	scanner := bufio.NewScanner(input)
	scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
		if atEOF && len(data) == 0 {
			return 0, nil, nil // 输入耗尽:结束扫描
		}
		if i := bytes.Index(data, []byte(" | ")); i >= 0 {
			return i + 3, data[:i], nil // 跳过分隔符,交出前段
		}
		if atEOF {
			return len(data), data, nil // 最后一段没有分隔符
		}
		return 0, nil, nil // 数据不足:请求更多输入
	})

	for scanner.Scan() {
		fmt.Println("field:", scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		panic(err)
	}
}

The SplitFunc contract

A SplitFunc receives the bytes currently available plus an atEOF flag and returns advance, token, err. The implementation here covers all four cases: end of input, a found “ | “ separator (advance i+3, hand back data[:i]), a final unterminated segment at EOF (advance len(data), return all of it), and not enough data yet (return 0, nil, nil to ask for more).

How the scan runs

bufio.NewScanner wraps a strings.Reader over “user=ada | action=login | ip=203.0.113.7”. The for scanner.Scan() loop prints each field with a field: label, so the run yields user=ada, then action=login, then ip=203.0.113.7. After the loop, scanner.Err() panics on any error instead of failing silently.

Where this applies

Built-in split functions only know lines, words, and a few byte-run shapes; a custom delimiter like “ | “ needs exactly this three-branch function.

Interactive Tools for This Topic

FAQ

What does returning 0, nil, nil from a SplitFunc mean?
It tells Scanner that the buffer does not yet contain a complete token; Scanner fetches more input and calls the function again.
Why does the final branch check atEOF?
At end of input there will never be more bytes, so the remaining data is returned as the last token with advance set to its full length; without that branch a trailing segment would be dropped.