bytes

Guided tour · Formatting & Strings · pkg.go.dev →

The strings package, but for []byte. Plus Buffer (a mutable growable byte buffer) and NewReader.

Search and slice manipulation

Most functions mirror the strings package but take and return []byte.

Contains, Index, HasPrefix

bytes.Contains([]byte("gopher"), []byte("ph"))   // true
bytes.Index([]byte("gopher"), []byte("ph"))      // 2
bytes.HasPrefix([]byte("gopher"), []byte("go"))  // true

Split, Fields, Join

bytes.Split([]byte("a,b,c"), []byte(","))  // [[97] [98] [99]]
bytes.Fields([]byte("  hi  there  "))      // [[104 105] [116 104 101 114 101]]
bytes.Join([][]byte{{'a'}, {'b'}}, []byte("-")) // "a-b"

ToUpper, TrimSpace, Replace

bytes.ToUpper([]byte("Go"))              // "GO"
bytes.TrimSpace([]byte("  hi\n"))        // "hi"
bytes.ReplaceAll([]byte("aaa"), []byte("a"), []byte("b")) // "bbb"

bytes.Equal — fast byte-slice equality

Faster than string(a) == string(b) because it skips the allocation. Safe with crypto/subtle's ConstantTimeCompare for secrets.

bytes.Equal([]byte("a"), []byte("a"))  // true

bytes.Buffer — growable byte buffer

Implements io.Reader and io.Writer. Zero value is ready to use.

Write and retrieve

var b bytes.Buffer
b.WriteString("hello")
b.WriteByte(' ')
fmt.Fprintf(&b, "%d", 42)
fmt.Println(b.String())   // "hello 42"
fmt.Println(b.Len())      // 8
Output
hello 42
8

Read from a buffer — it's also an io.Reader

b := bytes.NewBufferString("one\ntwo\n")
scanner := bufio.NewScanner(b)
for scanner.Scan() {
    fmt.Println("line:", scanner.Text())
}
Output
line: one
line: two

Reset + reuse — avoid reallocation

Call Reset to clear the buffer for reuse without throwing the underlying slice away.

var b bytes.Buffer
b.WriteString("first")
b.Reset()
b.WriteString("second")
fmt.Println(b.String())
Output
second

bytes.Reader — treat a []byte as an io.Reader

NewReader is cheap and supports Seek

r := bytes.NewReader([]byte("hello world"))
r.Seek(6, io.SeekStart)
buf := make([]byte, 5)
r.Read(buf)
fmt.Println(string(buf))
Output
world