Junior — Middle
What are the features of string traversal in programming?
sobes.tech AI
Answer from AI
In Go, strings are represented as a sequence of bytes, but they often contain characters in UTF-8 encoding, where one character (rune) can occupy multiple bytes. When iterating over a string by index (for example, for i := 0; i < len(s); i++), you are iterating over bytes, not characters, which can lead to incorrect handling of multi-byte characters.
To correctly iterate over characters, the for range loop is used, which iterates over runes (Unicode code points):
s := "Привет"
for i, r := range s {
fmt.Printf("index: %d, character: %c\n", i, r)
}
Here, i is the index of the first byte of the rune in the string, and r is the rune itself. This is important for proper handling of multilingual texts and characters outside ASCII.