Byte Slices
Let’s learn about byte slices in Go.
We'll cover the following
What are byte slices?
A byte slice is a slice of the byte
data type ([]byte
). Go knows that most byte
slices are used to store strings and so it makes it easy to switch between this type and the string
type. There is nothing special in the way we can access a byte slice compared to the other types of slices. What is special is that Go uses byte slices for performing file I/O operations because they allow us to determine with precision the amount of data we want to read or write to a file. This happens because bytes are a universal unit among computer systems.
Note: Because Go does not have a
char
data type, it usesbyte
andrune
for storing character values. A singlebyte
can only store a single ASCII character, whereas arune
can store Unicode characters. However, a rune can occupy multiple bytes.
Coding example
The small byteSlices.go
program that follows illustrates how we can convert a byte
slice into a string
and vice versa, which we need for most file I/O operations.
Get hands-on with 1400+ tech skills courses.