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.
data := []byte(" key=value ") trimmed := bytes.TrimSpace(data) fmt.Println(string(trimmed))
Try it
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.
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
==. Usebytes.Equal, which treatsniland an empty slice as equal, orbytes.Comparefor ordering (-1, 0, +1). - Results often share memory.
TrimSpace,Split,CutandFieldsreturn sub-slices of the input, so changing one changes the other. Usebytes.Clonewhen you need independence. bytes.Indextakes a[]byteseparator, so literals need a conversion:[]byte("x").IndexBytetakes a plainbyte.- Same semantics as
strings. Whatever you know aboutstrings.Cutorstrings.Fieldsapplies, including how an empty separator behaves. - Choose by data type, not speed. Converting
string(b)allocates and copies, so for large buffers stay inbytes; for small values readability usually wins. - Text encoding is UTF-8. Case conversion and
Mapoperate on runes, not single bytes.