实现说明
Scanner ErrTooLong 上调 token 上限可以归结为函数 main。
这个示例中仅有的重复出现在 for scanner.Scan() 里。
使用要点
- 这里没有依赖树——平台本身就是全部依赖。
- 演示输出是带标签的(
token len:、first pass:、second pass:),每个操作都会留下自己的一行标注。
常见问题
运行「Scanner ErrTooLong 上调 token 上限」会打印什么?
整个文件跑完,输出行以 token len:、first pass:、second pass: 这类前缀开头。
核心语句
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
代码示例
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
longLine := strings.Repeat("x", 70000)
input := longLine + "
short line
"
// the default token cap is 64KiB: the long line stops the scan with bufio.ErrTooLong
scanner := bufio.NewScanner(strings.NewReader(input))
for scanner.Scan() {
fmt.Println("token len:", len(scanner.Bytes()))
}
fmt.Println("first pass:", scanner.Err())
// Buffer raises the token limit: initial size, then maximum
scanner = bufio.NewScanner(strings.NewReader(input))
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
for scanner.Scan() {
fmt.Println("token len:", len(scanner.Bytes()))
}
fmt.Println("second pass:", scanner.Err())
}