Iterating Over Maps in Go: Examples and Use Cases
In Go, you can iterate over a map using a for range loop. When iterating over a map, the loop provides you with both the key and the value for each entry in the map. Below are several ways to iterate over a map in Go, along with detailed examples to illustrate different use cases.
Simple Iteration Over a Map
Here's a basic example of iterating over a map:
package main
import (
"fmt"
)
func main() {
myMap := map[string]int{
"Alice": 30,
"Bob": 25,
"Carol": 28,
}
for key, value := range myMap {
fmt.Printf("Key: %s, Value: %d\n", key, value)
}
}
Iterating Over Keys Only
If you only need the keys, you can ignore the values by using the blank identifier _:
package main
import (
"fmt"
)
func main() {
myMap := map[string]int{
"Alice": 30,
"Bob": 25,
"Carol": 28,
}
for key := range myMap {
fmt.Printf("Key: %s\n", key)
}
}
Iterating Over Values Only
Similarly, if you only need the values, you can ignore the keys:
package main
import (
"fmt"
)
func main() {
myMap := map[string]int{
"Alice": 30,
"Bob": 25,
"Carol": 28,
}
for _, value := range myMap {
fmt.Printf("Value: %d\n", value)
}
}
Checking Existence of a Key While Iterating
You can use the if statement inside the loop to check for specific conditions, such as the existence of a key:
package main
import (
"fmt"
)
func main() {
myMap := map[string]int{
"Alice": 30,
"Bob": 25,
"Carol": 28,
}
searchKey := "Bob"
for key, value := range myMap {
if key == searchKey {
fmt.Printf("%s found with value %d\n", key, value)
break
}
}
}
Modifying Values While Iterating
You can also modify the map's values while iterating. Note that you can't directly modify the iteration variable value. Instead, you must access and modify the map entry by its key:
package main
import (
"fmt"
)
func main() {
myMap := map[string]int{
"Alice": 30,
"Bob": 25,
"Carol": 28,
}
for key := range myMap {
myMap[key] += 1
}
fmt.Println("Updated map:", myMap)
// Output: Updated map: map[Alice:31 Bob:26 Carol:29]
}
Example with Structs
You can iterate over a map that has more complex data types such as structs:
package main
import (
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
people := map[int]Person{
1: {Name: "Alice", Age: 30},
2: {Name: "Bob", Age: 25},
3: {Name: "Carol", Age: 28},
}
for id, person := range people {
fmt.Printf("ID: %d, Name: %s, Age: %d\n", id, person.Name, person.Age)
}
}
Practical Example: Counting Word Frequency
Here's a practical example that counts the frequency of words in a sentence:
package main
import (
"fmt"
"strings"
)
func wordCount(sentence string) map[string]int {
words := strings.Fields(sentence)
wordMap := make(map[string]int)
for _, word := range words {
wordMap[word]++
}
return wordMap
}
func main() {
sentence := "this is a test this is only a test"
frequency := wordCount(sentence)
for word, count := range frequency {
fmt.Printf("Word: %s, Count: %d\n", word, count)
}
}
Output:
Word: this, Count: 2
Word: is, Count: 2
Word: a, Count: 2
Word: test, Count: 2
Word: only, Count: 1
Conclusion
Iterating over a map in Go is straightforward with the for range loop, which provides a simple and efficient way to access both keys and values. By leveraging various patterns like ignoring keys or values, checking conditions, or modifying values during iteration, you can handle a wide range of use cases involving maps in Go. Understanding these patterns enables you to write more versatile and effective code when working with maps.