On Mon, 11 Apr 2016 17:35:21 -0000 Jan Mercl <
0xj...@gmail.com> wrote:
>
> Slice is a value. The range evaluates its argument only once. Any
> subsequent changes to the slice value cannot change what the range argument
> evaluated to.
>
> Yet there is a danger. When the range argument is resliced anywhere else,
> including inside the loop, the program may later mistakenly use more/less
> elements than the range loop actually processed.
Both appending & reslicing in the loop seems to be safe.
x := []int{0, 1, 2, 3}
for _,v := range x {
fmt.Println(v)
//uncomment one of the three lines below
//if v < len(x) { x = x[v:] }
//x = append(x, v+len(x))
//x = nil
}
Looks like the slice value is cached. Not sure if that is an
implementation or language property.
Map seems to behave differently:
x := map[int]int{0:0, 1:1, 2:2, 3:3}
for k,v := range x {
fmt.Println(k, v)
delete(x,k+1)
}
This prints
0 0
2 2
So it appears a map is not cached. This behavior can be
explained but the following behavior is strange...
x := map[int]int{0:0, 1:1, 2:2, 3:3}
for k,v := range x {
fmt.Println(k, v)
x[len(x)] = len(x)
}
This prints anywhere from 4 to 7 lines. I would have expected
this loop to never terminate (or if cached, iterate exactly
four times).