Range over UTF-8 strings
Range over UTF-8 strings
With for i, r := range s, i is the byte offset where a decoded rune begins and r is the rune value. Go advances over the UTF-8 encoding, not one byte at a time. Use %U to print the Unicode code point and %c to print a rune as text.
package main
import ( "fmt")
func main() { for i, r := range "Aé🙂" { fmt.Printf("%d %U\n", i, r) }}Offsets are 0, 1 and 3 because the first two encodings take one and two bytes. A single-variable range over a string returns byte offsets, not rune values.
Expected output:
0 U+00411 U+00E93 U+1F642Compare byte and rune iteration
package main
import ( "fmt")
func main() { s := "é" for i := 0; i < len(s); i++ { fmt.Printf("%02x ", s[i]) } fmt.Println() for _, r := range s { fmt.Printf("%U\n", r) }}The index loop visits both bytes, whereas range decodes one code point. When range encounters an invalid UTF-8 encoding, it yields U+FFFD and advances one byte; the original string is not repaired.
Expected output:
c3 a9 U+00E9Try it locally
Use range to print byte offsets and runes for "سA".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strings and Unicode 04: Range over UTF-8 strings
Check the lesson objective before moving on.
What is i in for i, r := range s?
What does one-variable range over a string yield?