Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท bytes, unicode and text

Go bytes package

Overview of Go's bytes package: search, split, trim, compare and transform []byte values with the same API as strings, plus Buffer and Reader types.

The bytes package is the []byte twin of strings. Almost every function in strings has a counterpart here with the same name and the same meaning, except that it takes and returns byte slices: bytes.Contains, bytes.Split, bytes.TrimSpace, bytes.ToUpper and so on.

You reach for it when data arrives as bytes (network reads, file contents, hashing output, io.ReadAll) and converting it to a string just to search or trim would waste an allocation. It also holds bytes.Buffer for growable byte storage and bytes.NewReader for reading a slice as an io.Reader.

Go
data := []byte("  key=value  ")
trimmed := bytes.TrimSpace(data)
fmt.Println(string(trimmed))

Try it

Go The strings API on byte slices

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Comparing and cloning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

What the package contains

Group Functions and types
Compare Equal, EqualFold, Compare
Search Contains, ContainsAny, ContainsRune, Count, HasPrefix, HasSuffix, Index, IndexByte, IndexAny, LastIndex
Split and join Split, SplitN, Fields, Join, Cut, CutPrefix, CutSuffix, and the iterator forms Lines, SplitSeq, FieldsSeq (Go 1.24)
Change ToUpper, ToLower, Title (deprecated), Repeat, Replace, ReplaceAll, Map, Runes
Trim Trim, TrimSpace, TrimLeft, TrimRight, TrimPrefix, TrimSuffix, TrimFunc
Copy Clone (Go 1.20)
Types Buffer, Reader

Usage notes

  • Slices cannot be compared with ==. Use bytes.Equal, which treats nil and an empty slice as equal, or bytes.Compare for ordering (-1, 0, +1).
  • Results often share memory. TrimSpace, Split, Cut and Fields return sub-slices of the input, so changing one changes the other. Use bytes.Clone when you need independence.
  • bytes.Index takes a []byte separator, so literals need a conversion: []byte("x"). IndexByte takes a plain byte.
  • Same semantics as strings. Whatever you know about strings.Cut or strings.Fields applies, including how an empty separator behaves.
  • Choose by data type, not speed. Converting string(b) allocates and copies, so for large buffers stay in bytes; for small values readability usually wins.
  • Text encoding is UTF-8. Case conversion and Map operate on runes, not single bytes.