C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
String: For clearer display, we convert a byte slice into string with the string() built-in method.
Len: A byte slice has a length, which we retrieve with len. And we can access individual bytes.
Golang program that introduces byte slices
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])
}
Output
[97 98 99]
abcd
4
97
Result: As with strings.Index, bytes.Index returns the index if a sequence matches. Otherwise it returns -1.
IndexGolang program that uses bytes.Index
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")
}
}
Output
2
cat not found
Warning: This is a special syntax form. If we try to append a string with the three periods following it, we get an error.
Golang program that appends string to byte slice
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)
}
Output
[97 98 99 100 101 102]
Golang program that copies string to byte slice
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)
}
Output
3
[99 97 116 0]