Start Coding

Topics

Go For Loop: Mastering Iteration in Go

The for loop is a fundamental control structure in Go programming. It provides a powerful and flexible way to iterate over collections, perform repetitive tasks, and control program flow.

Basic Syntax

Go's for loop is versatile and can be used in several ways. The most common form is:

for initialization; condition; post {
    // loop body
}
  • Initialization: Executed once before the loop starts
  • Condition: Checked before each iteration
  • Post: Executed at the end of each iteration

Examples

1. Standard For Loop

for i := 0; i < 5; i++ {
    fmt.Println(i)
}

This loop prints numbers from 0 to 4.

2. While-like Loop

Go doesn't have a while keyword, but you can use for to create a while-like loop:

sum := 1
for sum < 1000 {
    sum += sum
}
fmt.Println(sum)

Advanced Usage

Infinite Loop

Create an infinite loop using:

for {
    // code to be executed
}

Use Go Break and Continue statements to control the loop's execution.

For-Range Loop

Iterate over arrays, slices, maps, or strings using the Go Range keyword:

fruits := []string{"apple", "banana", "cherry"}
for index, value := range fruits {
    fmt.Printf("Index: %d, Value: %s\n", index, value)
}

Best Practices

  • Keep loop bodies short and focused for better readability
  • Use meaningful variable names for loop counters
  • Consider using Go Break and Continue for complex loop logic
  • Be cautious with infinite loops to avoid program hangs

Performance Considerations

For loops in Go are efficient, but consider these tips for optimal performance:

  • Avoid unnecessary allocations inside loops
  • Use Go Range for iterating over large collections
  • Consider unrolling loops for small, fixed iterations

Master the for loop, and you'll have a powerful tool for controlling program flow in Go. Combined with other Go features like Go Goroutines and Go Channels, loops become even more powerful for concurrent programming.