capypad
0 day streak
go / beginner
Snippet

The Versatile for Loop

Go has only one loop construct: for. It can operate as a classic three-part for loop, a while-style loop, or an infinite loop with break. The range clause iterates over slices, arrays, maps, and strings with index and value.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main
import "fmt"
 
func main() {
// Classic counter loop
for i := 0; i < 3; i++ {
fmt.Printf("Counter: %d\n", i)
}
// While-style loop
count := 3
for count > 0 {
fmt.Printf("Countdown: %d\n", count)
count--
}
// Infinite loop with break
sum := 0
for {
sum++
if sum > 5 {
break
}
}
fmt.Printf("Sum: %d\n", sum)
// Range iteration
fruits := []string{"apple", "banana", "cherry"}
for i, fruit := range fruits {
fmt.Printf("%d: %s\n", i, fruit)
}
}
Breakdown
1
for i := 0; i < 3; i++
Classic C-style loop with initialization, condition, and post-statement
2
for count > 0
While-style: only condition present, loop runs until condition is false
3
for { sum++; if sum > 5 { break } }
Infinite loop with break for early exit when condition is met
4
for i, fruit := range fruits
Range returns index and value for each element; use _ to ignore index