Skip to main content
eLearner.app
Module 2 · Lesson 2 of 57/50 in the course~10 min
Module lessons (2/5)

for: the only loop

Go has a single loop construct: for. No while, no do-while, no foreach (that arrives in the next lesson with range). A single keyword covers all cases thanks to three forms.

The three forms of for

Classic three-clause form

Identical to C/Java:

Go
for i := 0; i < 5; i++ {
    fmt.Println(i)
}

i has scope limited to the for. The three clauses are optional (you can omit any of them) but the ; remain if you omit an intermediate one.

"while" form: condition only

In Go, while is simply a for with a single bool expression:

Go
i := 0
for i < 5 {
    fmt.Println(i)
    i++
}

Infinite form

Without clauses, the loop never terminates (unless break/return):

Go
for {
    if exitCondition() {
        break
    }
    doWork()
}

It is the pattern for event handling loops, servers, retry policies.

break, continue and labels

break exits the innermost loop, continue skips to the next iteration:

Go
for i := 0; i < 10; i++ {
    if i%2 == 0 {
        continue       // salta i pari
    }
    if i > 7 {
        break          // ferma il ciclo
    }
    fmt.Println(i)     // 1 3 5 7
}

To exit nested loops there are labels (rare but useful):

Go
Esterno:
for i := 0; i < 3; i++ {
    for j := 0; j < 3; j++ {
        if i*j == 4 {
            break Esterno   // esce da entrambi
        }
    }
}

No , operator like in C

In Go you cannot write for i, j := 0, 10; i < j; i, j = i+1, j-1: the post expression does not accept multiple assignments. Use Go's multiple assignment syntax:

Go
for i, j := 0, 10; i < j; i, j = i+1, j-1 {
    fmt.Println(i, j)
}

This instead works because i, j = i+1, j-1 is a single multiple assignment.

Try it

Exercise#go.m2.l2.e1
Attempts: 0Loading…

Print the numbers from 0 to 4 inclusive with a classic three-clause for.

Loading editor…
Show hint

`for init; cond; post { ... }` — here init is `i := 0`.

Solution available after 3 attempts

Exercise#go.m2.l2.e2
Attempts: 0Loading…

Sum into total all numbers from 1 to 10 inclusive using the 'while' form of for.

Loading editor…
Show hint

'while' form: `for <condition> { ... }`.

Solution available after 3 attempts

Quiz#go.m2.l2.e3
Ready

Which form represents an infinite loop in Go?

Go
// (a) for i := 0; i < 10; i++ { ... }
// (b) for cond { ... }
// (c) for { ... }
Answer options

Recap

  • A single keyword for with three forms: classic, while, infinite.
  • break / continue optionally with a label for nested loops.
  • Label Name: before the for, used sparingly.
  • No , as an operator: use the multiple assignment i, j = ..., ....