Copy Buffers With io.CopyBuffer
Pass your own buffer to io.CopyBuffer so repeated transfers reuse one allocation, then cap the transfer length with io.CopyN and read the remainder.
Code
package main
import (
"bytes"
"fmt"
"io"
"strings"
)
func main() {
src := strings.NewReader(strings.Repeat("payload line\n", 4))
// 自带缓冲区:长度必须为正,同一块内存在多次拷贝之间复用
buf := make([]byte, 16)
var dst bytes.Buffer
n, err := io.CopyBuffer(&dst, src, buf)
if err != nil {
panic(err)
}
fmt.Println("copied bytes:", n, "lines:", strings.Count(dst.String(), "\n"))
// CopyN 只搬前 N 字节,剩下的留在源里继续读
src2 := strings.NewReader("0123456789")
var head bytes.Buffer
n2, err := io.CopyN(&head, src2, 4)
if err != nil {
panic(err)
}
rest, err := io.ReadAll(src2)
if err != nil {
panic(err)
}
fmt.Printf("head %q rest %q copied %d\n", head.String(), string(rest), n2)
}The way it runs
Copy Buffers With io.CopyBuffer is built around the function main.
err is tested at 3 places, and a non-nil one aborts the run with panic(err).
Points of care
- No package manager involved — every call resolves to a built-in API.
- The snippet does not return errors — any non-nil
errends the run immediately.
Putting it to use
Signature: func main()
The run emits 2 labeled sections — copied bytes:, head — one per step.
Core lines
if err != nil {
panic(err)
}
buf := make([]byte, 16)
Interactive Tools for This Topic
FAQ
- Does the snippet panic on failure?
- It stops. All 3 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
- What does Copy Buffers With io.CopyBuffer print when run?
- The script runs standalone; its 2 labeled outputs include `copied bytes:`, `head`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.