Strings and runes
- Version
- 1.27
- Review
- Draft
Summary#
A string is a sequence of bytes, and len counts those bytes. A rune holds one Unicode code point. Ranging over a string decodes UTF-8 and yields each rune with its starting byte index.
Syntax#
count := utf8.RuneCountInString(text)
for index, r := range text {}
runes := []rune(text)
Example#
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
city := "Hu\u1ebf" // Huế
fmt.Println(len(city), utf8.RuneCountInString(city))
for index, r := range city {
fmt.Printf("byte %d: %c %U\n", index, r, r)
}
fmt.Printf("byte at 2: %#x\n", city[2])
fmt.Println("valid prefix:", utf8.ValidString(city[:3]))
runes := []rune(city)
fmt.Println(len(runes), string(runes[2]))
combined := "e\u0302\u0301" // one visible letter
fmt.Println(utf8.RuneCountInString(combined))
}
Expected output#
5 3
byte 0: H U+0048
byte 1: u U+0075
byte 2: ế U+1EBF
byte at 2: 0xe1
valid prefix: false
3 ế
3
Common mistakes#
Slicing at an arbitrary byte index can cut a rune in half. When decoding invalid UTF-8, range emits U+FFFD for each invalid byte. Use utf8.ValidString if you need to reject invalid data. A rune count can differ from the number of visible characters because combining marks are separate code points.
Version applicability#
The syntax and example work from Go 1.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0