Range Basics
In Golang, the range
keyword provides a powerful and concise way to iterate over various data structures. It simplifies the process of traversing collections like slices, arrays, maps, and channels.
Basic Syntax
The range
keyword follows a straightforward syntax that works across different data types:
for index, value := range collection {
// Iteration logic
}
Iteration Types
Slice and Array Iteration
When iterating over slices and arrays, range
returns two values: the index and the element.
fruits := []string{"apple", "banana", "cherry"}
for index, fruit := range fruits {
fmt.Printf("Index: %d, Fruit: %s\n", index, fruit)
}
Map Iteration
For maps, range
provides the key and corresponding value:
ages := map[string]int{
"Alice": 30,
"Bob": 25,
}
for name, age := range ages {
fmt.Printf("Name: %s, Age: %d\n", name, age)
}
Ignoring Values
Sometimes you might not need both index and value. Golang allows you to use the blank identifier _
:
// Ignore index
for _, fruit := range fruits {
fmt.Println(fruit)
}
// Ignore value
for index := range fruits {
fmt.Println(index)
}
graph TD
A[Range Iteration] --> B{Data Structure}
B --> |Slice/Array| C[Efficient O(n)]
B --> |Map| D[Less Predictable Performance]
B --> |Channel| E[Sequential Access]
In LabEx's Go programming environments, understanding range
iteration is crucial for writing efficient and readable code.
Key Takeaways
Feature |
Description |
Flexibility |
Works with multiple data structures |
Readability |
Simplifies iteration logic |
Performance |
Generally efficient for most use cases |
By mastering range
iteration, developers can write more expressive and concise Golang code.