-1
func main() {
    a1 := []int{0, 1, 2, 3}

    for i, v := range a1 {
        fmt.Println(i, v)

        if i == 0 {
            a1 = a1[2:]
        }
    }

    fmt.Println(a1)
}

Real output:

0 0
1 1
2 2
3 3
[2 3]

I think a1 has changed when i == 0, so why does v still output the value of original a1?I know the number of iterations in range has been determined, but I'm still confused about this result

wayne502
  • 19
  • 2
  • 2
    You iterate over the original value of `a1`, assigning a new value to the variable does not change that. – bereal May 05 '20 at 16:40

1 Answers1

2

From the language specification on For statements with range clause:

The range expression x is evaluated once before beginning the loop, with one exception: if at most one iteration variable is present and len(x) is constant, the range expression is not evaluated.

mkopriva
  • 35,176
  • 4
  • 57
  • 71