Introduction
In Go, maps are collections of key-value pairs where each key is unique. Iterating over a map allows you to access both the keys and their associated values. This guide will demonstrate how to iterate over a map in Go.
Problem Statement
Create a Go program that:
- Declares and initializes a map.
- Iterates over the map to print each key-value pair.
Example:
- Input: A map with key-value pairs:
{"Apple": 5, "Banana": 3, "Cherry": 7} - Output:
Apple: 5 Banana: 3 Cherry: 7
Solution Steps
- Import the fmt Package: Use
import "fmt"for formatted I/O operations. - Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Create and Initialize the Map: Use a map literal to create and initialize a map with some key-value pairs.
- Iterate Over the Map: Use a
forloop with therangekeyword to iterate over the map. - Display Each Key-Value Pair: Use
fmt.Printlnto display each key and its corresponding value.
Go Program
package main
import "fmt"
/**
* Go Program to Iterate Over a Map
* Author: https://www.javaguides.net/
*/
func main() {
// Step 1: Create and initialize the map
fruitMap := map[string]int{
"Apple": 5,
"Banana": 3,
"Cherry": 7,
}
// Step 2: Iterate over the map using a for loop with range
for key, value := range fruitMap {
// Step 3: Display each key-value pair
fmt.Println(key, ":", value)
}
}
Explanation
Step 1: Create and Initialize the Map
- A map is created and initialized using a map literal. For example,
fruitMap := map[string]int{"Apple": 5, "Banana": 3, "Cherry": 7}creates a map where the keys are strings representing fruit names, and the values are integers representing quantities.
Step 2: Iterate Over the Map
- The
forloop with therangekeyword is used to iterate over the map. The loop iterates over each key-value pair in the map. The variablekeyholds the key, and the variablevalueholds the corresponding value.
Step 3: Display Each Key-Value Pair
- Inside the loop,
fmt.Printlnis used to print each key-value pair in the formatkey: value.
Output Example
Example 1:
Apple : 5
Banana : 3
Cherry : 7
Example 2:
If you have a map with different data:
fruitMap := map[string]int{
"Mango": 12,
"Orange": 4,
"Grape": 9,
}
Output:
Mango : 12
Orange : 4
Grape : 9
Example 3:
If you have an empty map:
fruitMap := map[string]int{}
Output:
(No output, as the map is empty.)
Conclusion
This Go program demonstrates how to iterate over a map using a for loop with the range keyword. It covers basic programming concepts such as map creation, initialization, and iteration in Go. This example is useful for beginners learning Go programming and understanding how to work with maps effectively.