For statements with
range
clause…
The iteration variables may be declared by the “range” clause using a form of short variable declaration (
:=
). In this case their scope is the block of the “for” statement and each iteration has its own new variables [Go 1.22] (see also “for” statements with a ForClause).
We’ve already talked at some length about the scope of variables in other forms of for loops. For statements with range clauses work pretty much exactly the same way. So there’s not much new to cover here.
As with other for loops, if you use short variable declarations in your for/range statement, then each iteration of the loop creates new variable(s), which are scoped to the loop.
Also, as with other forms of for loops, if you use loop variables, but omit the short declaration, then you must define the variables prior to the loop, and in that case the scope follows standard scoping rules, and you do not get a unique variable instance for each iteration of the loop. Here’s an example:
var i int
fmt.Println("before", i)
for i = range 3 {
fmt.Println("during", i)
}
fmt.Println("after", i)
This code outputs:
before 0
during 0
during 1
during 2
after 2
… If the range expression is a (possibly untyped) integer expression
n
, the variable has the same type as if it was declared with initialization expressionn
. Otherwise, the variables have the types of their respective iteration values.
That is to say that when ranging over an integer, the loop variable, if present, gets the same type as the integer type argument to range
:
for i := range 1 {
fmt.Printf("%T", i)
}
for i := range int8(8) {
fmt.Printf("%T", i)
}
This code outputs:
int
int8
In the first case, i
gets the same as the default type for an untyped integer constant. In the second, it gets the explicit type of int8
.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)