Terminating statements
…
A “for” statement in which:
- there are no “break” statements referring to the “for” statement, and
- the loop condition is absent, and
- the “for” statement does not use a range clause.
Put another way, a for
statement is terminating if it either never ends (an infinite loop), or it unconditionally terminates.
This one “bit” me the other day, as I was refactoring code for a client. (Speaking of clients—I have some availability starting in May for a new client. Interested in having me work with you?)
The code I came across looked something like this:
for {
select {
case x := <-someChannel:
/* do something interesting */
}
}
And my linter told me I could simplify this code to:
for x := range someChannel {
/* do something interesting */
}
Looks good, right? Simpler code FTW!
The only problem?
By making that change, the for
loop was no longer a terminating statement, because it now had a range clause—it was no longer an infinite loop. As a result, the code stopped compiling, because there was no return
statement after the for
loop in the function. Ooops!
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)