A byte
is an 8-bit unsigned int
. In Go we often use byte slices. And the "bytes" package provides helper methods for byte slices (similar to strings).
We use methods, like append()
, to build byte slices. We can specify them with string
literals. Methods like bytes.Index
help us test and change bytes.
This program introduces byte slices. We create a byte slice from a string
literal "abc." We append a byte
to a byte slice.
string
with the string()
built-in method.len
. And we can access individual bytes.package main import "fmt" func main() { values := []byte("abc") fmt.Println(values) // Append a byte. values = append(values, byte('d')) // Print string representation of bytes. fmt.Println(string(values)) // Length of byte slice. fmt.Println(len(values)) // First byte. fmt.Println(values[0]) }[97 98 99] abcd 4 97
Index
Here we import the "bytes" package at the top (in the import statement). We call bytes.Index
to locate the sequence with the byte
values equal to "dog."
strings.Index
, bytes.Index
returns the index if a sequence matches. Otherwise it returns -1.package main import ( "bytes" "fmt" ) func main() { values := []byte("a dog") // Search for this byte sequence. result := bytes.Index(values, []byte("dog")) fmt.Println(result) // This byte sequence is not found. result = bytes.Index(values, []byte("cat")) if result == -1 { fmt.Println("cat not found") } }2 cat not found
Append
string
In Go we can use append()
on a byte slice with a string
argument. We must specify the three periods after the string
to append the string
.
string
with the three periods following it, we get an error.package main import "fmt" func main() { value := []byte("abc") // Append a string to a byte slice with special syntax. value = append(value, "def"...) fmt.Println(value) }[97 98 99 100 101 102]
string
into bytesThe copy()
built-in can copy a string
into a byte slice. Here we create an empty 4-element byte slice. Then we copy a three-element string
into it.
package main import "fmt" func main() { // Create an empty byte slice of length 4. values := make([]byte, 4) // Copy string into bytes. animal := "cat" copied := copy(values, animal) fmt.Println(copied) fmt.Println(values) }3 [99 97 116 0]
Buffer
We can use the bytes.Buffer
type to quickly append large pieces of byte
data together. Many helpful methods, like WriteString
, are available.
With bufio.ScanBytes
, we can use Scan()
to read each individual byte
in a file. We can test and store them as required.
Byte slices can be used much like strings in the Go language. We can create byte slices from string
literals. And the "bytes" package helps us manipulate and test our data.