Buffered Writes And Explicit Flush
bufio.Writer stages small writes in a buffer until Flush hands them on, and Buffered reports exactly how many bytes are still pending.
Code
package main
import (
"bufio"
"bytes"
"fmt"
)
func main() {
var out bytes.Buffer
w := bufio.NewWriter(&out)
// 写入先落在缓冲区,底层 writer 还什么都看不到
fmt.Fprintln(w, "step 1: buffered")
fmt.Println("before flush, bytes written:", out.Len())
// Flush 才真正交给底层 writer;丢弃前不 Flush 数据就丢了
if err := w.Flush(); err != nil {
panic(err)
}
fmt.Println("after flush, bytes written:", out.Len())
// Buffered 报告缓冲区里还没刷出的字节数
fmt.Fprint(w, "step 2")
fmt.Println("pending before second flush:", w.Buffered())
w.Flush()
fmt.Println("final content:", out.String())
}Inside the snippet
The snippet is organized around the function main.
Nothing continues past an unchecked error — 1 if err != nil branch, each ending in panic(err).
What to watch for
- Nothing but the runtime is needed — zero packages, zero install steps.
- Adapting this to library code usually means replacing the
panic(err)calls with error returns the caller can branch on.
Putting it to use
The demo output is labeled (before flush, bytes written:, after flush, bytes written:, pending before second flush:), so the output doubles as a step-by-step trace of what the file did.
The core lines of the flow
fmt.Fprintln(w, "step 1: buffered")
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.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- How are errors reported?
- By aborting: each of the 1 `err != nil` branches calls `panic(err)`, so a failure stops the program at the point it is detected.
- What does Buffered Writes And Explicit Flush print when run?
- Running the file directly is enough — expect labeled output lines such as `before flush, bytes written:`, `after flush, bytes written:`, `pending before second flush:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.