Go is known as a simple language, with straightforward concepts. For loops may be one of rare exceptions to that straightforward character, with three different forms:
For statements
A “for” statement specifies repeated execution of a block. There are three forms: The iteration may be controlled by a single condition, a “for” clause, or a “range” clause.
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . Condition = Expression .
Well, let’s dive on in, then, with the first of the three forms:
For statements with single condition
In its simplest form, a “for” statement specifies the repeated execution of a block as long as a boolean condition evaluates to true. The condition is evaluated before each iteration. If the condition is absent, it is equivalent to the boolean value true.
for a < b { a *= 2 }
A for loop of this form can operate on any boolean expression, whether it’s a single boolean variable, an expression that resolves to a boolean, or a function call:
for active { // active is of type bool
for a <= 3 {
for rows.Next() {
The text also mentions that the condition may be omitted, in which case it’s treated as true. This means the following two coe samples are functionally identical:
for true {
for {
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)