Range conclusion

July 5, 2024

Today we finish up with some final notes, and a big example, from the spec section on for statements.

For statements with range clause

If the iteration variables are not explicitly declared by the “range” clause, they must be preexisting. In this case, the iteration values are assigned to the respective variables as in an assignment statement.

I actually discussed this case yesterday, so won’t go into it again.

… If the range expression is a (possibly untyped) integer expression n, n too must be assignable to the iteration variable;

This is just to say that in an expression like this:

for i = range n

n’s type must be assignable to i.

That means this:

var i int8
for i = range int(10) {
	/* .. */
}

is invalid:

cannot use int(10) (constant 10 of type int) as int8 value in range clause

… if there is no iteration variable, n must be assignable to int.

So you can’t range over non-integers:

for range float64(10) {

produces:

cannot range over float64(10) (constant 10 of type float64)

Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe