For statements with
rangeclause…
The range expression
xis evaluated once before beginning the loop, with one exception: if at most one iteration variable is present andlen(x)is constant, the range expression is not evaluated.
The first part of this seems pretty self-evident, as it follows the same pattern as a for statement with a for clause: The expression needs to be evaluated once before the loop executes.
But this one has an exception. Let’s look at that to make sure we understand it.
First “if at most one iteration variable is present”. This means our code looks something like this:
for i := range x {
This form works for any of the supported types, but the next condition limits us more: “and len(x) is constant”.
len(x) is only constant in a few cases: When x is an array, or a string constant or literal.
But why? Why is it okay to not execute the range expression in such a case?
for x := range "Hello, 世界" {
Because we never need the result of that evaluation! All we (the compiler/runtime) care about in this case is the number of elements, since that’s what the first and only loop variable represents. And it’s a constant, so it’s known at compilation time. This tells us that the compiler is actually optimizing our code to be simpler, in effect turning the above for loop into:
for x := range len("Hello, 世界") {
which can in effect be further simplified to:
for x := range 11 {
Or this given a variable declaration var a [3]int, this:
for x := range a {
to this:
for x := range 3 {
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)