The byte type in Go is simply an alias for uint8, representing an unsigned 8-bit integer with a range from 0 to 255. It is primarily used to handle raw binary data and individual characters in strings, as Go strings are immutable sequences of bytes.
You typically encounter byte when working with file I/O, network protocols, or low-level string manipulation. Because it is an alias for uint8, you can use it anywhere a uint8 is expected, but using byte explicitly signals to other developers that you are dealing with raw data or character encoding rather than a general-purpose counter.
Here is a practical example showing how to iterate over a string as a sequence of bytes and modify them:
package main
import "fmt"
func main() {
// Go strings are UTF-8 encoded byte sequences
s := "Hello"
// Convert string to a byte slice to allow modification
b := []byte(s)
// Iterate over bytes directly
for i := 0; i < len(b); i++ {
// b[i] is of type byte (alias for uint8)
// Convert to int for arithmetic if needed, or cast to rune for Unicode
b[i] = b[i] + 1
}
// Convert back to string
fmt.Println(string(b)) // Output: "Ifmmp"
}
When reading from files or network connections, the io.Reader interface returns data as []byte. This is efficient because it avoids the overhead of decoding UTF-8 runes unless you specifically need to handle multi-byte characters.
package main
import (
"fmt"
"os"
)
func main() {
// Read first 10 bytes from a file
data := make([]byte, 10)
file, _ := os.Open("example.txt")
n, _ := file.Read(data)
// data is a slice of bytes
fmt.Printf("Read %d bytes: %v\n", n, data)
// Access individual bytes
if n > 0 {
fmt.Printf("First byte value: %d (type: %T)\n", data[0], data[0])
}
}
Remember that while byte is convenient for ASCII and raw data, it does not represent a full Unicode character (rune) if the string contains non-ASCII characters. A single rune can be 1 to 4 bytes long. If you need to iterate over actual characters regardless of encoding, use a range loop over the string, which yields rune values, not byte values.