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.

GoCli Tooling

Code

snippet
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

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.