Bytes Buffer Assembly With Grow And Reset
Grow a bytes.Buffer once, append strings bytes and runes through the io.Writer interface, then Reset it to reuse the backing array across batches.
Code
package main
import (
"bytes"
"fmt"
)
func main() {
var buf bytes.Buffer
// Grow 一次性预估容量:后续写入不再触发多次扩容拷贝
buf.Grow(64)
buf.WriteString("rows:") // 追加字符串
buf.WriteByte(' ') // 追加单个字节
for _, item := range []string{"alpha", "beta", "gamma"} {
fmt.Fprintf(&buf, "%s=%d,", item, len(item)) // *bytes.Buffer 实现 io.Writer
}
buf.WriteRune('…') // 追加一个 UTF-8 码点(3 字节)
out := buf.Bytes() // 底层字节切片,读侧零拷贝
fmt.Println(len(out), buf.String())
// Reset 清零内容、保留容量:同一缓冲区可复用到下一批
buf.Reset()
fmt.Println("after reset: len", buf.Len(), "cap>=64:", buf.Cap() >= 64)
}Order of operations
Bytes Buffer Assembly With Grow And Reset reduces to the function main.
The loop for _, item := range []string{"alpha", "beta", "gamma"} is the only repeated construct.
Watch out for
- No external surface: all behavior comes from the standard library.
Using it
The demo output is labeled (after reset: len), so every printed line maps back to its originating operation.
Key statements
for _, item := range []string{"alpha", "beta", "gamma"} {
fmt.Fprintf(&buf, "%s=%d,", item, len(item)) // *bytes.Buffer 实现 io.Writer
}
Interactive Tools for This Topic
Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.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.
FAQ
- What does Bytes Buffer Assembly With Grow And Reset print when run?
- No setup needed: run the file and look for labeled lines like `after reset: len` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.