Runes vs Bytes
Understand Go string internals.
What Is a Go String?
In Go a string is an immutable sequence of bytes. The bytes usually hold UTF-8 encoded text, but Go never forces that.
- You cannot change a string in place.
- Its
lencounts bytes, not characters.
package main
import "fmt"
func main() {
s := "Go"
fmt.Println(s)
fmt.Println(len(s))
}Bytes Behind the Scenes
Indexing a string with s[i] returns a single byte (type byte, an alias for uint8).
For plain ASCII text each character is exactly one byte.
package main
import "fmt"
func main() {
s := "ABC"
fmt.Println(s[0])
fmt.Println(s[1])
fmt.Println(s[2])
}All lessons in this course
- Runes vs Bytes
- strings Package Functions
- strings.Builder
- Unicode and utf8