Runes
rune is an alias for int32, commonly used for a Unicode code point. A Go string stores bytes; decoding UTF-8 runes does not necessarily count user-perceived characters.
Separate a Unicode code point from the bytes used to encode it.
tally reports the longest word in a text. On an English file it works; on a French menu it says café has 5 letters. Nothing is broken — Go is counting bytes, and é takes two of them. Runes are how Go talks about characters instead.
The rule
A rune is one character; a string is bytes; count characters as runes.
A rune is an alias for int32 and holds one Unicode code point. Rune literals use single quotes:
r := 'é'
fmt.Println(r) // 233, the code point
fmt.Printf("%c\n", r) // é
fmt.Println('A') // 65A string is a read-only sequence of bytes, normally UTF-8. In UTF-8, plain English letters take one byte, but é takes two, most other scripts take two or three, and emoji take four. So:
s := "café"
fmt.Println(len(s)) // 5 (bytes)
fmt.Println(utf8.RuneCountInString(s)) // 4 (characters)
fmt.Println(len([]rune(s))) // 4
fmt.Println(s[3]) // 195, a byte, not a characterIndexing a string with s[i] gives a byte. To walk characters, use for range, which decodes UTF-8 for you:
for i, r := range "café" {
fmt.Println(i, string(r))
}
// 0 c
// 1 a
// 2 f
// 3 éi is the byte position where each character starts, and r is the rune. The unicode package works on runes: unicode.IsLetter(r), unicode.ToLower(r).