Bufio ReadSlice ErrBufferFull
Read a line longer than the buffer with bufio.Reader ReadSlice, handle ErrBufferFull by appending fragments, and compare it with ReadString.
Code
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
long := strings.Repeat("x", 20) + "\n" + "short line\n"
reader := bufio.NewReaderSize(strings.NewReader(long), 8)
var line []byte
fragments := 0
for {
// ReadSlice stops at the delimiter or when the buffer is full
chunk, err := reader.ReadSlice('\n')
line = append(line, chunk...)
fragments++
if err == bufio.ErrBufferFull {
fmt.Println("buffer full after", len(chunk), "bytes")
continue
}
if err != nil {
fmt.Println("read stopped:", err)
}
break
}
fmt.Println("fragments:", fragments)
fmt.Println("line length:", len(line))
fmt.Println("newline kept:", line[len(line)-1] == '\n')
// ReadString returns the whole line and hides the fragmentation
whole, err := bufio.NewReaderSize(strings.NewReader(long), 8).ReadString('\n')
fmt.Println("ReadString length:", len(whole), "error:", err)
fmt.Println("same line:", whole == string(line))
}Inside the snippet
Everything effective happens in main — the rest is wiring.
for is the loop where each element gets its work done. Nothing falls through silently — 1 checkpoint test err != nil on the way through.
Points of care
- The package manager never enters the picture: all calls are built-in.
Using it
Each run prints the 7 labeled blocks buffer full after, read stopped:, fragments:, line length:, newline kept:, ReadString length:, same line: in source order.
The key statements, annotated
if err != nil {
fmt.Println("read stopped:", err)
}
line = append(line, chunk...)
Interactive Tools for This Topic
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.
FAQ
- What does Bufio ReadSlice ErrBufferFull print when run?
- No setup needed: run the file and look for labeled lines like `buffer full after`, `read stopped:`, `fragments:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.