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


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 {


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 Go: Design Patterns for Real-World Projects now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.