Today we’ll look at the second, of three, types of for statements: Those with a for clause.
For statements with
for
clauseA “for” statement with a
ForClause
is also controlled by its condition, but additionally it may specify an init and a post statement, such as an assignment, an increment or decrement statement. The init statement may be a short variable declaration, but the post statement must not.ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . InitStmt = SimpleStmt . PostStmt = SimpleStmt .
for i := 0; i < 10; i++ { f(i) }
So a for statement with for clause differs from the simpler type we saw yesterday, the for statement with a single condition, in that it contains two additional statements. This works a lot like the simple statements we’ve already seen in if
, switch
, and select
statements, with the addition of a post statement, not just an init statement.
If non-empty, the init statement is executed once before evaluating the condition for the first iteration; the post statement is executed after each execution of the block (and only if the block was executed).
Let’s look at the execution order here, in detail. Given a simple for loop like this:
for i := 0; i < 3; i++ {
fmt.Println(i)
}
based on the above, the execution would look something like this, if broken out of a loop:
i := 0 // initial statement
if i < 3 { // i == 0, 0 < 3 so execute the block
fmt.Println(i) // Prints 0
i++ // Post statement only executes if the block executes
}
if i < 3 { // i == 1, 1 < 3 so execute the block
fmt.Println(i) // Prints 1
i++ // Post statement only executes if the block executes
}
if i < 3 { // i == 2, 2 < 3 so execute the block
fmt.Println(i) // Prints 2
i++ // Post statement only executes if the block executes
}
if i < 3 { // i == 3, 3 is not less than 3, so the block does not execute, and the loop ends
/* not executed */
}
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)