Go by Example: Byte Handling
Bytes are the fundamental unit of data in Go. This example explores the `byte` alias, `[]byte` slices for mutable data, and how to efficiently convert between strings and bytes using the `bytes` package.
Code
package main
import (
"bytes"
"fmt"
)
func main() {
// 1. The 'byte' alias
// 'byte' is exactly the same as 'uint8'.
var b byte = 65 // ASCII for 'A'
fmt.Printf("Byte: %d, Character: %c\n", b, b)
// 2. Byte Slices ([]byte)
// Unlike strings, byte slices are mutable.
data := []byte("Hello")
data[0] = 'J' // Change 'H' to 'J'
fmt.Println("Modified slice:", string(data))
// 3. String <-> Byte Conversion
// Converting creates a copy of the data (memory allocation).
str := "Go"
byteSlice := []byte(str)
byteSlice[0] = 'N'
fmt.Println("Original string:", str) // "Go" (immutable)
fmt.Println("Converted slice:", string(byteSlice)) // "No"
// 4. Using bytes.Buffer
// Efficient way to build strings or byte arrays (like StringBuilder).
var buf bytes.Buffer
buf.WriteString("Hello")
buf.WriteByte(',')
buf.WriteString(" World!")
fmt.Println("Buffer result:", buf.String())
// 5. Common bytes package functions
// The 'bytes' package is like 'strings' but for []byte.
src := []byte("go programming")
upper := bytes.ToUpper(src)
fmt.Printf("Upper: %s\n", upper)
}
Explanation
In Go, a byte is an alias for uint8. It represents a single byte of data (0-255). While strings are used for text, []byte (byte slice) is the standard type for raw binary data, network streams, and file I/O.
The key difference is mutability: strings are immutable (cannot be changed once created), whereas byte slices are mutable. This makes []byte essential when you need to modify data in place. Converting between string and []byte is easy (`[]byte(str)` and `string(bytes)`), but be aware that it typically causes a memory allocation because the data must be copied to ensure safety.
For efficient manipulation, the standard library provides the bytes package. It includes a Buffer type (similar to StringBuilder in Java/C#) which is highly recommended for concatenating strings or bytes to avoid unnecessary allocations.
- Alias:
byte==uint8. - Mutability: Strings are read-only; byte slices are read-write.
- Conversion:
[]byte("text")copies memory. - Performance: Use
bytes.Bufferfor building large strings.

