Skip to content

Go Loops

Loops are fundamental control structures that allow you to execute a block of code repeatedly. Go has only one looping construct, the for loop, but it’s versatile enough to cover various looping scenarios found in other languages (like while or do-while loops).

Go’s for loop can be used in several ways:

This form has an initialization statement, a condition expression, and a post statement.

package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Println("Iteration:", i) // Prints 0, 1, 2, 3, 4
}
}

By omitting the initialization and post statements, the for loop behaves like a while loop in other languages.

package main
import "fmt"
func main() {
n := 1
for n <= 5 {
fmt.Println("n is:", n)
n *= 2 // n becomes 1, 2, 4, 8 (loop exits when n=8)
}
}

If the condition is also omitted, it creates an infinite loop. Such loops must be exited using break or return statement from within the loop body, or by other means (e.g., panic).

package main
import (
"fmt"
"time"
)
func main() {
count := 0
for {
fmt.Println("Infinite loop iteration...")
time.Sleep(500 * time.Millisecond)
count++
if count >= 3 {
fmt.Println("Exiting infinite loop.")
break
}
}
}

Note: You can typically terminate an infinite loop in a command-line program by pressing Ctrl + C.

This form iterates over elements in various data structures like slices, arrays, strings, maps, and channels. It’s covered in detail in the “Go - Range” section.

Go provides statements to alter the normal flow of loop execution:

Control StatementDescription
breakTerminates the innermost for, switch, or select statement. Execution resumes at the statement immediately following the terminated loop/switch/select.
continueSkips the remainder of the current iteration of the innermost for loop. Execution proceeds to the post statement (if any) and then the condition for the next iteration.
gotoTransfers control to a labeled statement within the same function. Use of goto is generally discouraged as it can make code complex and hard to follow. It is rarely needed in idiomatic Go.

Example: break and continue

package main
import "fmt"
func main() {
// Using continue to print odd numbers
fmt.Println("Odd numbers up to 10 (using continue):")
for i := 1; i <= 10; i++ {
if i%2 == 0 { // If i is even
continue // Skip the rest of this iteration
}
fmt.Printf("%d ", i)
}
fmt.Println()
// Using break to find first number divisible by 3 and 5
fmt.Println("\nFinding first number divisible by 3 and 5 (using break):")
for i := 1; i <= 100; i++ {
if i%3 == 0 && i%5 == 0 {
fmt.Printf("Found: %d\n", i)
break // Exit the loop once found
}
}
}

You can have for loops inside other for loops. break and continue statements apply to the innermost loop unless a label is used.

package main
import "fmt"
func main() {
OuterLoop: // Label for the outer loop
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {
fmt.Printf("i=%d, j=%d\n", i, j)
if i == 2 && j == 2 {
fmt.Println("Breaking out of OuterLoop from inner loop")
break OuterLoop // Break statement with a label
}
}
}
}

The for loop is a powerful and flexible construct in Go, accommodating all common looping patterns.