Iteration over integers

July 3, 2024

I’m back from my holiday! I thought I’d send at least a few dalies over the last week while I was on vacation, but it wasn’t meant to be. But now that I’m back, we’ll pick up where we left off…


For statements with range clause

  1. For an integer value n, the iteration values 0 through n-1 are produced in increasing order. If n <= 0, the loop does not run any iterations.

This form of range was added recently, in Go 1.22, and it serves as a simple short cut. These two code snippets are functionally equivalent:

for x := 0; x < 10; x++ {
for x := range 10 {

It might be a bit counter-intuitive that you can use a negative integer value as the argument to range, without a runtime panic: “If n <= 0, the loop does not run any iterations.”

But I think this makes sense, if we consider it to be equivalent to the earlier form:

for x := 0; x < -3; x++ {

would also iterate 0 times, and would not panic.

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