Sobes.tech
Middle

What will the program output with range over a string and slice modification?

sobes.tech AI

Answer from AI

In Go, when iterating over a string with range, the iteration is over Unicode code points (runes), not bytes. If you modify a slice of the string during iteration, it can lead to unexpected results because strings in Go are immutable, and slices are created over the original data.

Example:

package main
import "fmt"

func main() {
    s := "hello"
    for i, r := range s {
        fmt.Printf("%d: %c\n", i, r)
        if i == 1 {
            s = "world" // modifying the string slice
        }
    }
}

The output will be:

0: h
1: e
2: l
3: l
4: o

Changing the string inside the loop does not affect the already running range, because range over a string works with the original data, and strings in Go are immutable. Therefore, the program will output the characters of the original string, not the new one.

Thus, changing a string during range iteration does not alter the behavior of the iteration, but it is not recommended to do so to avoid confusion.

What will the program output with range over a string… - sobes.tech