Sobes.tech
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:

  • i is the index of the current character in the string, of type int.
  • v is the value of the current character, of type rune (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.

What is iteration over a string using for range in… - sobes.tech