Sobes.tech
Junior — Middle

What results are obtained when iterating through the characters of a string sequentially?

sobes.tech AI

Answer from AI

When iterating over the characters of a string in Go (Golang), a for range loop is typically used, which iterates over runes — Unicode code points.

The result of such iteration is obtaining each character of the string as a rune value and its position (byte index).

Example:

package main
import (
    "fmt"
)

func main() {
    s := "Привет"
    for i, r := range s {
        fmt.Printf("Index: %d, Character: %c\n", i, r)
    }
}

The output will contain the index (in bytes) and the corresponding character. This is important because in UTF-8, characters can occupy a different number of bytes.

Thus, sequential iteration allows working correctly with Unicode strings, obtaining each character as a whole, not just individual bytes.