Practical Loop Examples
Real-World Loop Scenarios
1. Array Iteration
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Printf("Index: %d, Fruit: %s\n", index, fruit)
}
2. Sum Calculation
numbers := []int{1, 2, 3, 4, 5}
total := 0
for _, num := range numbers {
total += num
}
fmt.Println("Sum:", total)
Loop Patterns
Conditional Filtering
values := []int{10, 15, 20, 25, 30}
var evenNumbers []int
for _, value := range values {
if value % 2 == 0 {
evenNumbers = append(evenNumbers, value)
}
}
Mermaid Loop Flow Visualization
graph TD
A[Start Loop] --> B{Input Data}
B --> C[Iterate Through Elements]
C --> D{Apply Condition}
D -->|Match| E[Process Element]
D -->|No Match| F[Skip Element]
E --> G{More Elements?}
F --> G
G -->|Yes| C
G -->|No| H[End Loop]
Loop Type |
Use Case |
Performance |
Readability |
Standard For |
Fixed iterations |
High |
Good |
Range Loop |
Slice/Map iteration |
Moderate |
Excellent |
Conditional Loop |
Complex logic |
Variable |
Moderate |
Advanced Example: Prime Number Detection
func findPrimes(max int) []int {
primes := []int{}
for num := 2; num <= max; num++ {
isPrime := true
for divisor := 2; divisor * divisor <= num; divisor++ {
if num % divisor == 0 {
isPrime = false
break
}
}
if isPrime {
primes = append(primes, num)
}
}
return primes
}
Best Practices
- Choose the right loop type for your scenario
- Use
range
for simplicity
- Avoid unnecessary complexity
- Consider performance implications
LabEx recommends experimenting with these examples to deepen your understanding of Go loops and incrementation techniques.