Yesterday we saw some high-level examples of range statements. Let’s start into some of the details now.
For statements with
range
clause… For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.
RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
The formal definition there is pretty straight forward. But there are a number of nuances, which we’ll cover over the next few days.
The expression on the right in the “range” clause is called the range expression, its core type must be an array, pointer to an array, slice, string, map, channel permitting receive operations, or an integer.
That’s mostly a re-statement of the list we looked at yesterday, so we’ll just continue.
… As with an assignment, if present the operands on the left must be addressable or map index expressions; they denote the iteration variables. If the range expression is a channel or integer, at most one iteration variable is permitted, otherwise there may be up to two.
The point about the number of iteration variables permitted when ranging over channels is important. At least I find myself being tripped up by it from time to time. What it’s saying is that this is invalid:
for value, ok := range myChannel {
The only reason I find myself tripped up by this on occasion is that the other way to read a channel (with the <-
operator) allows both one, and two-variable forms:
value := <- myChannel
or
value, ok := <- myChannel
In this case, the second variable, ok
, is a boolean, which is set to true when a value is read from the channel, or false otherwise. But when ranging over a channel, this isn’t necessary. A successful read is already made apparent by the fact that the loop executes!
If the last iteration variable is the blank identifier, the range clause is equivalent to the same clause without that identifier.
In other words, these are equivalent:
for k, _ := range myMap {
and
for k := range myMap {
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)