O'Reilly logo

Learning Go Programming by Vladimir Vivien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required