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
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 mainimport "fmt"func main() {// Classic counter loopfor i := 0; i < 3; i++ {fmt.Printf("Counter: %d\n", i)}// While-style loopcount := 3for count > 0 {fmt.Printf("Countdown: %d\n", count)count--}// Infinite loop with breaksum := 0for {sum++if sum > 5 {break}}fmt.Printf("Sum: %d\n", sum)// Range iterationfruits := []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