Iterating Map Elements
Iteration Methods in Golang
Golang provides multiple ways to iterate through map elements, each with unique characteristics and use cases.
1. Range-Based Iteration
Basic Range Iteration
func main() {
// Create a sample map
fruits := map[string]int{
"apple": 5,
"banana": 3,
"orange": 7,
}
// Iterate through all key-value pairs
for key, value := range fruits {
fmt.Printf("Fruit: %s, Quantity: %d\n", key, value)
}
}
2. Iteration Patterns
Iteration Techniques Comparison
Method |
Key Access |
Value Access |
Performance |
Range Loop |
Full Access |
Full Access |
Recommended |
Keys Only |
Possible |
No |
Lightweight |
Values Only |
No |
Possible |
Limited Use |
3. Keys-Only Iteration
func main() {
cities := map[string]string{
"USA": "Washington",
"France": "Paris",
"Japan": "Tokyo",
}
// Iterate through keys only
for key := range cities {
fmt.Println("Country:", key)
}
}
4. Sorted Map Iteration
func main() {
// Maps are unordered, so use slice for sorting
scores := map[string]int{
"Alice": 95,
"Bob": 87,
"Charlie": 92,
}
// Extract and sort keys
keys := make([]string, 0, len(scores))
for k := range scores {
keys = append(keys, k)
}
sort.Strings(keys)
// Iterate in sorted order
for _, k := range keys {
fmt.Printf("%s: %d\n", k, scores[k])
}
}
Iteration Flow
graph TD
A[Start Map Iteration] --> B{Range Keyword}
B --> C[Access Key]
B --> D[Access Value]
C --> E[Process Key]
D --> F[Process Value]
E --> G[Continue/Exit Loop]
F --> G
- Avoid modifying map during iteration
- Use
len()
to check map size before iteration
- Be cautious with large maps
Common Pitfalls
- Concurrent map modification
- Assuming map order
- Not checking map initialization
Advanced Iteration Techniques
Filtering During Iteration
func main() {
numbers := map[string]int{
"a": 10,
"b": 20,
"c": 30,
"d": 40,
}
// Filter and collect values
var filtered []int
for _, value := range numbers {
if value > 20 {
filtered = append(filtered, value)
}
}
fmt.Println(filtered)
}
LabEx Recommendation
Practice different iteration techniques to become proficient in Golang map manipulation.
Best Practices
- Use range for most iterations
- Separate key and value processing when needed
- Consider performance for large maps