Skip to content

Go Loops (For and While)

Go only has one looping construct: the for loop. There is no while or do-while keyword in Go, but you can achieve the same behavior using for.

1. The Classic For Loop

The most basic type of loop, similar to C or Java.

1
2
3
4
5
6
7
8
9
package main
import "fmt"

func main() {
    // init; condition; post
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}

2. The "While" Style Loop

By omitting the initialization and post statements, for behaves exactly like a while loop.

1
2
3
4
5
i := 1
for i <= 3 {
    fmt.Println(i)
    i = i + 1
}

3. Infinite Loops

A for without any condition will run forever until you break out of it or return from the function.

1
2
3
4
for {
    fmt.Println("looping...")
    break // exit the loop
}

4. Continue and Break

  • continue: Skip the rest of the current iteration and start the next one.
  • break: Exit the loop entirely.
1
2
3
4
5
6
for n := 0; n <= 5; n++ {
    if n%2 == 0 {
        continue // skip even numbers
    }
    fmt.Println(n)
}

5. Loop over Collections (Range)

To iterate over arrays, slices, or maps, use the range keyword.

1
2
3
4
nums := []int{2, 3, 4}
for index, value := range nums {
    fmt.Printf("index: %d, value: %d\n", index, value)
}