Middle
What is iteration over a string using for range in Go? What are the variables i and v inside the loop, and what are their data types?
sobes.tech AI
Answer from AI
In Go, the for range construct is used to iterate over collections, including strings. When iterating over a string with for i, v := range str:
iis the index of the current character in the string, of typeint.vis the value of the current character, of typerune(Unicode code point).
This is important because in Go, strings are sequences of bytes, and range over a string returns rune characters, correctly handling multi-byte UTF-8 characters.
Example:
str := "Привет"
for i, v := range str {
fmt.Printf("Index: %d, Character: %c, Type: %T\n", i, v, v)
}
The output will show the byte indices of the start of each character and the characters themselves as runes.