bytes

bytes search and split helpers, Clone versus shared backing arrays, and Buffer.Bytes aliasing.

The bytes package works with slices of bytes: searching, splitting, joining, and buffering. It is a standard-library package, imported as "bytes", not a language built-in.

Several helpers return subslices of their input, and Buffer.Bytes aliases the buffer. If you mutate those slices, the original data changes too. Use Clone when you need a copy that does not share storage.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
bytes.Equal, bytes.Compare, bytes.Contains, bytes.Index, bytes.Join, bytes.Split, bytes.Replace, bytes.TrimSpaceCompare or search byte slices, join them, split them, replace a limited number of matches, or trim Unicode white space.
bytes.Clone, bytes.Cut, Buffer.BytesClone copies a slice. Cut splits once around a separator but aliases s. Buffer.Bytes aliases the buffer until the next modification.

Search, compare, join, and split

Equal and Compare treat a nil slice as empty. Contains and Index search for a subslice; Index returns -1 when the separator is not present. Join concatenates slices with a separator. Split slices around every instance of a separator and, unlike Cut, is meant for all matches. Replace returns a copy, and a negative count replaces every instance. TrimSpace removes leading and trailing Unicode white space by returning a subslice.

bytes.Equal, bytes.Compare, bytes.Contains, bytes.Index, bytes.Join, bytes.Split, bytes.Replace, bytes.TrimSpace

func Equal(a, b []byte) bool
func Compare(a, b []byte) int
func Contains(b, subslice []byte) bool
func Index(s, sep []byte) int
func Join(s [][]byte, sep []byte) []byte
func Split(s, sep []byte) [][]byte
func Replace(s, old, new []byte, n int) []byte
func TrimSpace(s []byte) []byte

Compare or search byte slices, join them, split them, replace a limited number of matches, or trim Unicode white space.

ParameterDescription
a, b, sByte slices to compare, search, join, split, or trim. For Equal and Compare, a nil slice is equivalent to an empty slice.
sep, old, new, subsliceA separator, a subslice to find, or the old and new sequences for Replace.
nFor Replace, the maximum number of replacements. If n < 0, there is no limit.

Returns: Equal and Contains return a boolean. Compare returns -1, 0, or 1. Index returns a byte index or -1. Join, Split, Replace, and TrimSpace return byte slices.

  • Replace returns a copy of s. TrimSpace returns a subslice of s, so later writes to the result can change the original slice.
  • Split with an empty separator splits after each UTF-8 sequence. To cut around only the first separator, use Cut.
go
package main

import (
	"bytes"
	"fmt"
)

func main() {
	fmt.Println(bytes.Equal([]byte("ab"), []byte("ab")), bytes.Compare([]byte("a"), []byte("b")))
	fmt.Println(bytes.Contains([]byte("hello"), []byte("ell")), bytes.Index([]byte("hello"), []byte("l")))
	fmt.Printf("%s\n", bytes.Join([][]byte{[]byte("a"), []byte("b")}, []byte(",")))
	fmt.Printf("%q\n", bytes.Split([]byte("a,b,c"), []byte(",")))
	fmt.Printf("%s\n", bytes.Replace([]byte("aa"), []byte("a"), []byte("b"), 1))
	fmt.Printf("%q\n", bytes.TrimSpace([]byte("  x\n")))
}

Expected output

true -1
true 2
a,b
["a" "b" "c"]
ba
"x"

Official documentation →

Alias versus copy

Assigning a slice header copies the pointer, length, and capacity, so both variables share the same backing array. Clone returns a copy of b[:len(b)] that does not alias the original; Clone(nil) returns nil. Cut and CutPrefix return slices of the original input, not copies. Buffer.Bytes returns a slice that aliases the unread buffer content until the next buffer modification, so in-place edits are visible to later reads and to String.

bytes.Clone, bytes.Cut, Buffer.Bytes

func Clone(b []byte) []byte
func Cut(s, sep []byte) (before, after []byte, found bool)
func (b *Buffer) Bytes() []byte
func (b *Buffer) WriteString(s string) (n int, err error)
func (b *Buffer) String() string

Clone copies a slice. Cut splits once around a separator but aliases s. Buffer.Bytes aliases the buffer until the next modification.

ParameterDescription
b, sThe slice to copy or to split. Cut returns slices of this same array.
sepThe separator for Cut. If it is not found, Cut returns s, nil, false.

Returns: Clone returns a copy, or nil when b is nil. Cut returns the parts before and after the separator and whether the separator was found. Bytes returns the unread portion of the buffer. WriteString returns the number of bytes written and a nil error unless the buffer is too large, in which case it panics with ErrTooLarge. String returns the unread contents as a string.

  • A plain assignment such as alias := a does not copy the bytes. Changing alias[0] also changes a. Changing the clone does not.
  • CutPrefix is like Cut at the start of the slice and also returns a subslice of the original input.
  • The zero value of Buffer is ready to use. Do not keep a Bytes slice across Write, Read, Reset, or Truncate calls.
go
package main

import (
	"bytes"
	"fmt"
)

func main() {
	a := []byte("hello")
	alias := a
	cloned := bytes.Clone(a)
	alias[0] = 'H'
	fmt.Println(string(a), string(alias), string(cloned))
	fmt.Println(bytes.Clone(nil) == nil, bytes.Equal(nil, []byte{}))

	src := []byte("a=b")
	before, after, found := bytes.Cut(src, []byte("="))
	before[0] = 'A'
	fmt.Println(string(before), string(after), found, string(src))

	var buf bytes.Buffer
	buf.WriteString("hello")
	view := buf.Bytes()
	view[0] = 'H'
	fmt.Println(buf.String())
}

Expected output

Hello Hello hello
true true
A b true A=b
Hello

Official documentation →