Byte slices ([]byte)
- Version
- 1.27
- Review
- Draft
Summary#
A []byte stores a sequence of bytes you can edit. Convert a string to a byte slice to change individual bytes, then convert it back when a string is needed.
Syntax#
data := []byte("go")
data[0] = 'G'
updated := string(data)
Example#
package main
import "fmt"
func main() {
original := "go tools"
data := []byte(original)
data[0] = 'G'
fmt.Println(original)
fmt.Println(string(data))
}
Expected output#
go tools
Go tools
The second line changes the first ASCII byte. Both strings retain the non-breaking space between the two words.
Common mistakes#
A byte index refers to one byte. Unicode characters encoded with UTF-8 may occupy several bytes. Use rune-aware processing when the unit of work is a Unicode code point.
Version applicability#
Byte slices and both conversion forms in the example are available from Go 1.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0