Slice Iteration Techniques
Standard For Loop Iteration
Traditional Index-Based Iteration
fruits := []string{"apple", "banana", "orange"}
for i := 0; i < len(fruits); i++ {
fmt.Printf("Fruit %d: %s\n", i, fruits[i])
}
Range-Based Iteration
Basic Range Iteration
numbers := []int{10, 20, 30, 40, 50}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
Ignoring Index or Value
// Ignore index
for _, value := range numbers {
fmt.Println(value)
}
// Ignore value
for index := range numbers {
fmt.Println(index)
}
Advanced Iteration Techniques
Concurrent Slice Iteration
func processSlice(slice []int, ch chan int) {
for _, value := range slice {
ch <- value * 2
}
close(ch)
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
ch := make(chan int, len(numbers))
go processSlice(numbers, ch)
for value := range ch {
fmt.Println(value)
}
}
Iteration Strategies
graph TD
A[Slice Iteration] --> B[Traditional For Loop]
A --> C[Range-Based Iteration]
A --> D[Concurrent Iteration]
Comparative Analysis
Iteration Method |
Performance |
Readability |
Flexibility |
Traditional For |
High |
Low |
Limited |
Range-Based |
Moderate |
High |
Flexible |
Concurrent |
Complex |
Moderate |
Highly Flexible |
- Use range for most scenarios
- Avoid unnecessary allocations
- Prefer index-based iteration for simple loops
Memory-Efficient Iteration
largeSlice := make([]int, 1000000)
for i := 0; i < len(largeSlice); i++ {
// Process without creating additional copies
value := largeSlice[i]
// Perform operations
}
Special Iteration Scenarios
Nested Slice Iteration
matrix := [][]int{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
}
for i, row := range matrix {
for j, value := range row {
fmt.Printf("Element at [%d][%d]: %d\n", i, j, value)
}
}
Best Practices
- Choose the right iteration method
- Be mindful of performance
- Use range for most use cases
- Leverage concurrent iteration when appropriate
Explore more slice iteration techniques with LabEx's advanced Golang programming tutorials.