Table of Contents

Go Stdlib Wiki: package bytes

1. Overview

The Go standard library package bytes provides functions for working with byte slices ([]byte). It is like strings, but for raw bytes—useful for file/network data, buffers, and binary-safe operations.

byte /baɪt/ = byte (đơn vị dữ liệu)

slice /slaɪs/ = lát cắt / mảng động

binary-safe /ˈbaɪnəri seɪf/ = an toàn với dữ liệu nhị phân (không “hỏng” khi gặp byte lạ)

 import "bytes" 

2. bytes vs strings

Use strings when you have string.

Use bytes when you have []byte.

Common conversion:

s := string(b) // []byte -> string (copies data)
b := []byte(s) // string -> []byte (copies data)

convert /kənˈvɝːt/ = chuyển đổi

copy /ˈkɑːpi/ = sao chép

3. Common function groups

3.1 Prefix / Suffix checks

bytes.HasPrefix(b, prefix []byte) bool

bytes.HasSuffix(b, suffix []byte) bool

 bytes.HasPrefix([]byte("golang"), []byte("go")) // true bytes.HasSuffix([]byte("golang"), []byte("ng")) // true 

bytes.Contains(b, subslice []byte) bool

bytes.Index(b, subslice []byte) int

bytes.LastIndex(b, subslice []byte) int

bytes.Count(b, sep []byte) int

subslice /ˈsʌb.slaɪs/ = lát cắt con

 bytes.Contains([]byte("hello world"), []byte("world")) // true bytes.Index([]byte("banana"), []byte("na")) // 2 bytes.LastIndex([]byte("banana"), []byte("na")) // 4 bytes.Count([]byte("banana"), []byte("na")) // 2 

3.3 Split / Join

bytes.Split(b, sep []byte) [][]byte

bytes.SplitN(b, sep []byte, n int) [][]byte

bytes.Fields(b) [][]byte — split around whitespace

bytes.Join(s [][]byte, sep []byte) []byte

 parts := bytes.Split([]byte("a,b,c"), []byte(",")) // [[97] [98] [99]] (each inner slice is bytes for "a", "b", "c")
 
joined := bytes.Join([][]byte{[]byte("a"), []byte("b")}, []byte("-"))
// []byte("a-b")

3.4 Replace / Repeat

bytes.Replace(b, old, new []byte, n int) []byte

bytes.ReplaceAll(b, old, new []byte) []byte

bytes.Repeat(b []byte, count int) []byte

 bytes.Replace([]byte("a a a"), []byte("a"), []byte("b"), 2) // []byte("b b a") bytes.ReplaceAll([]byte("a a a"), []byte("a"), []byte("b")) // []byte("b b b") bytes.Repeat([]byte("go"), 3) // []byte("gogogo") 

3.5 Trim

bytes.TrimSpace(b []byte) []byte

bytes.Trim(b []byte, cutset string) []byte

bytes.TrimPrefix(b, prefix []byte) []byte

bytes.TrimSuffix(b, suffix []byte) []byte

Note: bytes.Trim takes cutset as a string, not []byte.

 bytes.TrimSpace([]byte(" hello \n")) // []byte("hello") bytes.Trim([]byte("...hello..."), ".") // []byte("hello") bytes.TrimPrefix([]byte("https://a.com"), []byte("https://")) // []byte("a.com") 

cutset /ˈkʌtˌset/ = tập ký tự cần cắt

3.6 Compare & Equal

bytes.Equal(a, b []byte) bool — true if identical bytes

bytes.Compare(a, b []byte) int — like lexicographic compare (-1, 0, 1)

bytes.EqualFold(s, t []byte) bool — case-insensitive (ASCII)

equal /ˈiːkwəl/ = bằng nhau

lexicographic /ˌlɛksɪˈkɒɡræfɪk/ = so sánh theo thứ tự từ điển

 bytes.Equal([]byte("go"), []byte("go")) // true bytes.Compare([]byte("a"), []byte("b")) // -1 bytes.EqualFold([]byte("Go"), []byte("gO")) // true (ASCII) 

4. Buffers & streaming helpers

4.1 bytes.Buffer

bytes.Buffer is a growable buffer of bytes implementing io.Reader and io.Writer.

buffer /ˈbʌfər/ = bộ đệm

growable /ˈɡroʊəbl/ = có thể tăng kích thước

implements /ˈɪmplɪments/ = hiện thực (interface)

 var buf bytes.Buffer buf.WriteString("hello") buf.WriteByte(' ') buf.Write([]byte("world"))
 
out := buf.Bytes() // []byte view (be careful: can change if buffer grows)
s := buf.String() // "hello world"

Common uses:

Build []byte efficiently in a loop

Read/write with APIs expecting io.Reader / io.Writer

4.2 bytes.NewBuffer / bytes.NewReader

bytes.NewBuffer(b []byte) *bytes.Buffer — buffer initialized with bytes

bytes.NewReader(b []byte) *bytes.Reader — read-only io.Reader, supports io.Seeker

 r := bytes.NewReader([]byte("data")) p := make([]byte, 2) r.Read(p) // reads "da" 

reader /ˈriːdər/ = bộ đọc

seeker /ˈsiːkər/ = bộ “seek” (nhảy vị trí đọc)

5. Practical mini-recipes

5.1 Check a binary header (magic bytes)

pngMagic := []byte{0x89, 0x50, 0x4E, 0x47}
isPNG := bytes.HasPrefix(fileBytes, pngMagic)

5.2 Split HTTP-like lines

lines := bytes.Split(data, []byte("\r\n"))

5.3 Trim and normalize incoming data

clean := bytes.TrimSpace(data)

6. Notes & pitfalls

Many functions return slices that may reference the same underlying array. Avoid keeping them long-term if the original buffer changes.

bytes.Buffer.Bytes() returns a view; writing more may reallocate and change it.

For Unicode-aware text processing, prefer strings/rune logic after decoding to string.

underlying array /ˌʌndərˈlaɪɪŋ əˈreɪ/ = mảng nền bên dưới

reallocate /ˌriːˈæləˌkeɪt/ = cấp phát lại