For statements with
range
clause…
- For an array, pointer to array, or slice value
a
, the index iteration values are produced in increasing order, starting at element index 0. If at most one iteration variable is present, the range loop produces iteration values from 0 up tolen(a)-1
and does not index into the array or slice itself. For anil
slice, the number of iterations is 0.
From this above paragraph, we can be assured that ranging over an array, pointer to array, or slice, will operate in a defined order–from index 0, upward. While this is probably what anyone would expect, it’s good to know this is part of the spec, and that someone can’t one day surprise us by writing a Go compiler that arbitrarily operates in reverse order, or random order.
What’s probably more interesting from this paragraph, though, is that when there’s at most a single iteration variable, that is, a loop in the form of for x := range a
(as opposed to for x, y := range a
, with two variables), we never actually index into the array/slice. This is because all that’s needed to assign to the loop variables is a generated iteration from 0 to len(a)-1
, which can be done without indexing into a
. Functionally, of course, it doesn’t matter that we don’t index into a
, it’s purely an optimization in performance.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)