Runes vs bytes
A byte is an 8-bit value (uint8). A rune is a Unicode code point (int32). Strings and []byte are sequences of bytes. Decoding UTF-8 produces runes, which may take one to four bytes each.
Detailed Explanation
You want the "first character" of a name. s[0] is the first byte. For "André" that is 'A'. For "€10" that is 0xe2, the first byte of the euro sign, not the euro sign. A rune is the code point '\u20ac'. UTF-8 encodes that rune as three bytes.
range over a string yields runes. for i, r := range s sets r to the next code point and i to its starting byte index. Invalid UTF-8 becomes '\uFFFD' (replacement character) and consumes one byte. range over []byte yields bytes, not runes.
Conversions. []rune(s) decodes the whole string into code points. string(runes) encodes them back. []byte(s) is the raw bytes. string(r) for a single rune is the UTF-8 of that code point. string(b) for a byte is a one-byte string, which is only valid UTF-8 for ASCII.
Indexing is bytes. There is no s[i] that returns a rune at character position i. To get the nth rune you range, or you convert to []rune (which allocates). For ASCII-only identifiers, bytes and runes coincide and s[i] is fine.
utf8 package. utf8.DecodeRuneInString, utf8.RuneCountInString, and utf8.ValidString are the tools when range is not enough. Do not invent a for i := 0; i < len(s); i++ decoder.
What it costs. Ranging a string decodes as it goes; there is no extra allocation. []rune(s) allocates a slice of 4-byte code points. If you only need to count or walk, range. If you need random access to the nth character, you pay for the conversion or you store []rune from the start. Most text processing in Go stays on string or []byte and walks sequentially.
Code Examples
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "€10"
fmt.Println(len(s), utf8.RuneCountInString(s)) // 5 3
fmt.Printf("%x\n", s[0]) // e2, not the euro
for i, r := range s {
fmt.Printf("%d %q\n", i, r)
}
}func firstRune(s string) (rune, bool) {
for _, r := range s {
return r, true
}
return 0, false
}func asRunes(s string) []rune {
return []rune(s)
}Common Gotchas
`s[i]` is not the ith character
it is the ith byte and can land in the middle of a rune.
`len([]rune(s))` allocates
use `utf8.RuneCountInString` when you only need the count.
Invalid UTF-8 is still a legal `string`
hashing and I/O should treat it as bytes; UI should validate.
`byte` and `rune` are aliases of `uint8` and `int32`
they are not a separate UTF-16 storage model like Java `char`.