For Loop Basics
Introduction to For Loops in Golang
In Golang, the for
loop is a fundamental control structure used for repetitive tasks. Unlike some programming languages that offer multiple loop types, Go simplifies looping with a single, versatile for
loop that can handle various iteration scenarios.
Basic Syntax of For Loops
The standard for loop in Go follows this basic structure:
for initialization; condition; post-iteration {
// loop body
}
Let's break down each component:
Component |
Description |
Example |
Initialization |
Optional statement executed before first iteration |
i := 0 |
Condition |
Boolean expression checked before each iteration |
i < 10 |
Post-iteration |
Statement executed at the end of each iteration |
i++ |
Simple Numeric Iteration
Here's a classic example of iterating through numbers:
package main
import "fmt"
func main() {
// Iterate from 0 to 4
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
Infinite and Conditional Loops
Go provides flexible loop constructs:
flowchart TD
A[Start Loop] --> B{Condition}
B -->|True| C[Execute Loop Body]
C --> B
B -->|False| D[Exit Loop]
Infinite Loop
for {
// runs forever until break
}
Conditional Loop
for condition {
// runs while condition is true
}
Range-based Iteration
Go's for
loop can iterate over slices, arrays, maps, and strings:
// Iterating over a slice
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Printf("Index: %d, Value: %s\n", index, fruit)
}
Best Practices
- Use
break
to exit loops early
- Use
continue
to skip current iteration
- Avoid complex loop conditions
By mastering these for
loop techniques, you'll write more efficient and readable code in Golang. Practice with LabEx to enhance your skills!