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
|
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 x:=0; x < 10; x++ { ... } |
For range |
Used to iterate over an expression representing a collection of items stored in an array, string (array of rune), slice, map, and channel: for i, val := range values { ... } |
Notice, as with all other control statements in Go, the for
statements do not use parentheses around their expressions. All statements...