Next: , Up: The First Echo Command using a for Loop   [Index]


1.5.1 The for Loop Statement

The for loop is the only loop statement in Go. It has a number of forms, one of which is illustrated here:

  for initialization; condition; post {
          // zero or more statements
}

Parentheses are never used around the three components of a for loop. The braces are mandatory, however, and the opening brace must be on the same line as the post statement.

The optional initialization statement is executed before the loop starts. If it is present, it must be a simple statement, that is,

The condition is a boolean expression that is evaluated at the beginning of each iteration of the loop; if it evaluates to ‘true’, the statements controlled by the loop are executed.

The post statement is executed after the body of the loop, then the condition is evaluated again.

The loop ends when the condition becomes false.

Any of these parts may be omitted. If there is no initialization and no post, the semicolons may also be omitted:

while Loop using a for Loop

// a traditional "while" loop
for condition {
        // ...
}

Listing 1.3: While Loop

An Infinite Loop using a for Loop

 // a traditional infinite loop
for {
        // ...
}

Listing 1.4: Infinite Loop

the loop is infinite, though loops of this form may be terminated in some other way, like a break or return statement.


Next: Iterate Using the range Operator, Up: The First Echo Command using a for Loop   [Index]