Go For Loops: Iterating with Precision

Go's for loop is a versatile construct that allows you to execute code repeatedly. Unlike some languages, Go doesn't have separate while or do-while loops. Instead, the for loop can be adapted to various iteration patterns.



Basic For Loop Structure

The general syntax of a for loop in Go is:

Syntax

for initialization; condition; post-statement {
  // code to be executed
}
            

Use code with caution.

  • Initialization: Executed once before the loop starts. Often used to declare loop variables.
  • Condition: Evaluated before each iteration. If true, the loop continues; if false, the loop terminates.
  • Post-statement: Executed after each iteration. Often used to increment or decrement loop variables.

Example:

Code Snippet

package main

import "fmt"

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

Use code with caution.

For Loop as a While Loop

By omitting the initialization and post-statement, you can create a while-like loop:

Code Snippet

package main

import "fmt"

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

Use code with caution.

Infinite Loop

If you omit all three components, you create an infinite loop:

Syntax

for {
  // This loop will run forever unless a break statement is used
}
            

Use code with caution.

The range Keyword

The range keyword is particularly useful for iterating over arrays, slices, strings, maps, and channels.

Syntax

for index, value := range collection {
  // code to be executed for each element
}
            

Use code with caution.

Example:

Code Snippet

package main

import "fmt"

func main() {
  numbers := []int{2, 3, 4, 5}
  for index, num := range numbers {
    fmt.Println("Index:", index, "Value:", num)
  }
}
            

Use code with caution.

Break and Continue Statements

break: Terminates the loop entirely.

continue: Skips the current iteration and moves to the next.

Code Snippet

for i := 0; i < 10; i++ {
  if i == 5 {
    break
  }
  if i%2 == 0 {
    continue
  }
  fmt.Println(i)
}
            

Use code with caution.

Nested Loops

You can nest for loops to create complex iteration patterns:

Code Snippet

for i := 0; i < 3; i++ {
  for j := 0; j < 3; j++ {
    fmt.Println(i, j)
  }
}
            

Use code with caution.

By mastering the for loop and its variations, you can efficiently handle repetitive tasks and iterate over different data structures in your Go programs.