The for Loop
The Classic Three-Part for Loop
Go's most familiar for loop has three parts separated by semicolons: an initializer, a condition checked before each iteration, and a post statement run after each iteration. This mirrors the classic C-style for loop found in many languages.
Example: The Classic Three-Part for Loop
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println("iteration", i)
}
}
Login to try C/C++/Java/PHP code in the editor
for as a while Loop
Dropping the init and post clauses and keeping only a condition turns for into the equivalent of a while loop found in other languages -- it keeps running as long as the condition stays true.
Example: for as a while Loop
package main
import "fmt"
func main() {
n := 1
for n < 100 {
n *= 2
}
fmt.Println("first power of two >= 100:", n)
}
Login to try C/C++/Java/PHP code in the editor
Infinite Loops
Omitting all three clauses produces an infinite loop, 'for { }', which runs forever unless something inside it breaks out or returns from the function. This form is often used for servers or workers that should run until explicitly stopped.
Note: Always pair an infinite for loop with a break, return, or os.Exit so the program has a way out.
Example: Infinite Loops
package main
import "fmt"
func main() {
count := 0
for {
count++
if count == 3 {
break
}
}
fmt.Println("stopped at:", count)
}
Login to try C/C++/Java/PHP code in the editor
Nested for Loops
Because for is Go's only loop construct, nested loops (a loop inside a loop) are written by simply placing one for statement inside another, commonly used for iterating over grids or combinations of two sequences.
Example: Nested for Loops
package main
import "fmt"
func main() {
for i := 1; i <= 3; i++ {
for j := 1; j <= 2; j++ {
fmt.Printf("(%d,%d) ", i, j)
}
}
fmt.Println()
}
Login to try C/C++/Java/PHP code in the editor
- Looking for a while or do-while keyword -- Go only has for, which can be written in while-style with just a condition.
- Forgetting the loop variable is scoped to the loop and modifying it inside expecting it to persist meaningfully after the loop ends.
- Writing an infinite 'for {}' without a break condition or return, accidentally hanging the program.
- Go has exactly one looping keyword, for, used in several styles.
- The classic three-part form is 'for init; condition; post { }'.
- 'for condition { }' behaves like a while loop in other languages.
- 'for { }' with no clauses loops forever until an explicit break or return.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: