The for statements

As a language related to the C-family, Go also supports for loop style control structures. However, as you may have come to expect by now, Go's for statements work interestingly differently and simply. The for statement in Go supports four distinct idioms, as summarized in the following table:

For Statement

Usage

For condition

Used to semantically replace while and do...while loops:

for x < 10 {

...

}

Infinite loop

The conditional expression may be omitted to create an infinite loop:

for {
...
}

Traditional

This is the traditional form of the C-family for loop with the initializer, test, and update clauses:

for x:=0; x < 10; x++ {
...
}

For range

Used to iterate over an expression representing a collection of items ...

Get Learning Go Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.