Skip to content
Go: Copy bytes.Buffer data before retaining a snapshot

Go: Copy bytes.Buffer data before retaining a snapshot

November 13, 2026

bytes.Buffer.Bytes exposes the buffer’s unread bytes without copying them. Clone that slice before retaining a snapshot across later buffer changes.

Set up

Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as bytes_buffer_owned_snapshot.go:

package main

import (
	"bytes"
	"fmt"
)

func main() {
	var buf bytes.Buffer
	buf.WriteString("hello")
	view := buf.Bytes()
	snapshot := bytes.Clone(view)
	view[0] = 'H'
	fmt.Printf("buffer=%q snapshot=%q\n", buf.String(), snapshot)
	buf.Reset()
	buf.WriteString("next")
	fmt.Printf("reused=%q snapshot=%q\n", buf.String(), snapshot)
}
go run bytes_buffer_owned_snapshot.go

Observed output:

buffer="Hello" snapshot="hello"
reused="next" snapshot="hello"

Read the result

Changing the view immediately changes the buffer. The cloned snapshot stays unchanged, including after the buffer is reset and reused. The example deliberately stops using the view before resetting the buffer.

Apply it carefully

The returned view is valid only until the next buffer modification, including reads that advance its unread portion. Copy before that boundary. Cloning these bytes costs an allocation and a byte copy, so keep the view for immediate use when ownership allows it. Copying does not make concurrent access to the buffer safe; coordinate that access separately.

See the Go standard-library reference.

Clean up

Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.

rm -- bytes_buffer_owned_snapshot.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on