bytes package implements functions for the manipulation of byte slices. It is analogous to the facilities of the strings package.
Key Functions
Comparison
Searching
Manipulation
Trimming
Case Conversion
Buffer Type
TheBuffer type is a variable-sized buffer of bytes with Read and Write methods.
Creating Buffers
Writing to Buffers
Reading from Buffers
Buffer Methods
Reader Type
AReader implements io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, io.ByteScanner, and io.RuneScanner by reading from a byte slice.
Practical Examples
Building a CSV-like structure
Parsing key-value pairs
Efficient string building
Performance Tips
- Use Buffer for concatenation - More efficient than repeated
append()calls - Preallocate Buffer capacity - Use
Grow()if you know the approximate size - Reuse Buffers - Call
Reset()to reuse buffers and reduce allocations - Choose appropriate functions -
Equalis optimized, faster than manual comparison
Relation to strings Package
Most functions inbytes have equivalents in the strings package:
bytes.Equal↔strings.EqualFoldbytes.Contains↔strings.Containsbytes.Index↔strings.Indexbytes.Split↔strings.Split- etc.
bytes when working with []byte, and strings when working with string.