Go > Core Go Basics > Control Flow > For loops

Basic For Loop in Go

This code snippet demonstrates the fundamental structure of a 'for' loop in Go, showcasing its versatility in iterating through a sequence of numbers.

Basic Structure

This snippet initializes a variable 'i' to 0. The loop continues as long as 'i' is less than 5. After each iteration, 'i' is incremented by 1. Inside the loop, the current value of 'i' is printed.

package main

import "fmt"

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

Concepts Behind the Snippet

The 'for' loop is a cornerstone of iterative programming. It provides a concise way to repeat a block of code a specific number of times or until a condition is met. It has three key components: initialization (executed once at the beginning), condition (evaluated before each iteration), and post statement (executed after each iteration).

Real-Life Use Case

Imagine you need to process a list of user IDs. A 'for' loop can be used to iterate through the list and perform an action for each user, such as retrieving their profile information from a database or sending them an email. This demonstrates looping through external data structures in this example.

Best Practices

  • Use meaningful variable names: Choose descriptive names for loop counters to enhance readability.
  • Keep the loop body concise: Complex logic should be factored out into separate functions.
  • Avoid unnecessary computations in the condition: If the condition can be pre-calculated, do so to improve performance.

Interview Tip

Be prepared to explain the different parts of a 'for' loop and how they control the loop's execution. Understand common errors, such as infinite loops, and how to debug them.

When to use them

Use 'for' loops when you know in advance how many times you need to repeat a block of code or when you have a clear condition for stopping the loop.

Alternatives

While loops and range-based for loops are common alternatives for iterating collections in other languages, in Go, the 'for' loop is flexible enough to cover most scenarios. However, 'range' is specifically used to iterate over slices, maps, and strings, providing both index and value.

Pros

  • Concise syntax: Go's 'for' loop is relatively easy to read and understand.
  • Versatile: It can be used for a variety of iteration patterns.
  • Efficient: 'for' loops are generally performant for most use cases.

Cons

  • Can be error-prone: Incorrect initialization, condition, or post statement can lead to unexpected behavior.
  • Less readable for complex iterations: For very complex iteration patterns, other control flow structures might be more appropriate.

FAQ

  • What happens if the condition in a 'for' loop is always true?

    If the condition is always true, the loop will run indefinitely, creating an infinite loop. You'll need to ensure there's a way to break out of the loop, such as a 'break' statement or by modifying a variable within the loop to eventually make the condition false.
  • How can I skip an iteration in a 'for' loop?

    You can use the 'continue' statement to skip the current iteration and proceed to the next one.