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:
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:
i := 0
for i < 5 {
fmt.Println(i)
i++
}Infinite form
Without clauses, the loop never terminates (unless break/return):
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:
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):
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:
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
Print the numbers from 0 to 4 inclusive with a classic three-clause for.
Show hint
`for init; cond; post { ... }` — here init is `i := 0`.
Solution available after 3 attempts
Sum into total all numbers from 1 to 10 inclusive using the 'while' form of for.
Show hint
'while' form: `for <condition> { ... }`.
Solution available after 3 attempts
Which form represents an infinite loop in Go?
// (a) for i := 0; i < 10; i++ { ... }
// (b) for cond { ... }
// (c) for { ... }Recap
- A single keyword
forwith three forms: classic, while, infinite. break/continueoptionally with a label for nested loops.- Label
Name:before thefor, used sparingly. - No
,as an operator: use the multiple assignmenti, j = ..., ....