A byte is Go’s alias for the unsigned 8-bit integer type uint8. Strings store immutable sequences of bytes, so byte positions are not necessarily character positions. section 5.0 section 5.2
The byte-indexing mistake
For s := "hêllo", ranging over the string visits rune-starting byte indexes: 0, 1, 3, 4, and 5. Printing s[i] prints one byte, producing corrupted output such as Ã, while len(s) returns 6 bytes rather than 5 runes. section 5.2
Choose the representation that matches the operation:
- Use the range value, for i, r := range s, when iterating over decoded runes; i is the starting byte index and r is the rune. section 5.2
- Convert with []rune(s) when you need rune indexes or direct rune-slice access; use []byte when operating on raw bytes. section 5.2 section 5.0
- Use utf8.RuneCountInString for rune counts only when the string is treated as UTF-8; strings can also contain arbitrary bytes. section 5.1 section 5.2
s := "hêllo" #1
for i := range s {
fmt.Printf("position %d: %c\n", i, s[i])
}
fmt.Printf("len=%d\n", len(s))
Inspect the failing loop and its concrete output to see how byte indexes diverge from rune positions. section 5.2






