Go for Loops

Welcome to The Coding College!

In Go, the for loop is the only looping construct, but it’s incredibly versatile and can handle a wide range of scenarios. This guide will cover everything you need to know about for loops in Go, from basic syntax to advanced use cases.

Why Use for Loops?

for loops are used to execute a block of code repeatedly based on a condition. They are essential for tasks like iterating over collections, performing repetitive computations, and automating workflows.

Basic Syntax

for initialization; condition; post {
    // Code to execute in each iteration
}
  • Initialization: Executes once before the loop starts (e.g., i := 0).
  • Condition: Evaluated before each iteration; the loop continues while this evaluates to true.
  • Post: Executes after each iteration (e.g., i++).

Example: Basic for Loop

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println(i) // Output: 0 1 2 3 4
    }
}

Types of for Loops in Go

Go supports various types of for loops to handle different scenarios.

1. Standard for Loop

for initialization; condition; post {
    // Loop body
}

Example:

for i := 1; i <= 10; i++ {
    fmt.Printf("Square of %d is %d\n", i, i*i)
}

2. Condition-Only Loop

You can omit the initialization and post statements for a simpler loop.

Example:

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

3. Infinite Loop

By omitting all three parts, you create an infinite loop.

Example:

for {
    fmt.Println("This will run forever")
    break // Use break to exit the loop
}

4. Range-Based Loop

The range keyword is used to iterate over collections like arrays, slices, maps, and strings.

Example: Iterating Over a Slice

numbers := []int{10, 20, 30, 40, 50}
for index, value := range numbers {
    fmt.Printf("Index: %d, Value: %d\n", index, value)
}

Example: Iterating Over a String

word := "GoLang"
for index, char := range word {
    fmt.Printf("Index: %d, Character: %c\n", index, char)
}

Control Statements in for Loops

Go provides break and continue to control the flow of loops.

1. break Statement

Exits the loop immediately.

Example:

for i := 1; i <= 10; i++ {
    if i == 5 {
        break // Exit the loop when i is 5
    }
    fmt.Println(i)
}

2. continue Statement

Skips the current iteration and moves to the next one.

Example:

for i := 1; i <= 10; i++ {
    if i%2 == 0 {
        continue // Skip even numbers
    }
    fmt.Println(i) // Output: 1 3 5 7 9
}

Nested for Loops

You can nest for loops to handle multi-dimensional data or complex logic.

Example: Multiplication Table

for i := 1; i <= 3; i++ {
    for j := 1; j <= 3; j++ {
        fmt.Printf("%d * %d = %d\n", i, j, i*j)
    }
}

Practical Examples

Example 1: Sum of Numbers

sum := 0
for i := 1; i <= 10; i++ {
    sum += i
}
fmt.Println("Sum:", sum) // Output: Sum: 55

Example 2: Iterating Over a Map

person := map[string]string{
    "name":    "Alice",
    "country": "USA",
    "job":     "Developer",
}

for key, value := range person {
    fmt.Printf("%s: %s\n", key, value)
}

Example 3: Finding Prime Numbers

for num := 2; num <= 20; num++ {
    isPrime := true
    for i := 2; i < num; i++ {
        if num%i == 0 {
            isPrime = false
            break
        }
    }
    if isPrime {
        fmt.Println(num, "is a prime number")
    }
}

Best Practices for for Loops

  1. Limit Nesting
    • Avoid deeply nested loops; refactor complex logic into functions.
  2. Use range for Collections
    • range simplifies iteration over arrays, slices, and maps.
  3. Optimize Condition Checks
    • Ensure the loop condition is efficient to avoid performance issues.
  4. Avoid Infinite Loops
    • Use infinite loops (for {}) cautiously and include exit conditions.

Common Mistakes

  • Off-by-One Errors
    • Carefully define loop bounds to avoid missing or extra iterations.
for i := 0; i < 10; i++ { // Correct
  • Unoptimized Conditions
    • Avoid complex or redundant conditions inside loops.
  • Skipping Initialization
    • Forgetting to initialize loop variables can lead to undefined behavior.

Conclusion

Go’s for loop is versatile, allowing you to handle simple iterations, collection traversal, and complex logic. By understanding its features and applying best practices, you can write efficient and readable loops in your programs.

Leave a Comment