Bufio Buffered Reads And Writes
Wrap file and network IO in bufio so many small reads and writes coalesce into few syscalls instead of one each.
Code
package main
import (
"bufio"
"bytes"
"fmt"
"strings"
)
func main() {
// 写:多次小写入先在缓冲区合并,Flush 时才落到底层
var sink bytes.Buffer
bw := bufio.NewWriterSize(&sink, 4096)
for i := 1; i <= 5; i++ {
fmt.Fprintf(bw, "line-%d\n", i)
}
fmt.Println("before flush, sink bytes:", sink.Len()) // 0
if err := bw.Flush(); err != nil {
fmt.Println("flush failed:", err)
}
fmt.Println("after flush, sink bytes:", sink.Len())
// 读:按行扫描,默认缓冲区避免每次读都进 syscall
scanner := bufio.NewScanner(strings.NewReader(sink.String()))
count := 0
for scanner.Scan() {
count++
}
if err := scanner.Err(); err != nil {
fmt.Println("scan failed:", err)
}
fmt.Println("scanned lines:", count)
}Tracing the logic
Bufio Buffered Reads And Writes comes down to the function main.
Iteration happens inside for i := 1; i <= 5; i++ — everything outside it runs once. Error handling is inline: 2 places test err != nil and branch immediately.
Points of care
- Nothing third-party is pulled in; the snippet is dependency-free.
Using it
The demo output is labeled (before flush, sink bytes:, flush failed:, after flush, sink bytes:), so every line of output can be traced to the operation that made it.
Key statements
if err := scanner.Err(); err != nil {
fmt.Println("scan failed:", err)
}
Interactive Tools for This Topic
FAQ
- What does Bufio Buffered Reads And Writes print when run?
- Execute the whole file; each printed line is prefixed with a label like `before flush, sink bytes:`, `flush failed:`, `after flush, sink bytes:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.