1. Introduction
Iterating over maps in Go is a fundamental technique that allows you to access every key-value pair within a map. This is especially useful when you need to perform operations on map data or extract information. In this blog post, we'll demonstrate how to loop through a map in Go.
2. Program Steps
1. Create and populate a map with sample data.
2. Iterate over the map using a for range loop.
3. Print out each key-value pair from the map.
3. Code Program
package main
import "fmt"
func main() {
// Step 1: Create and populate a map
phoneBook := map[string]string{
"Alice": "555-1234",
"Bob": "555-5678",
"Carol": "555-7890",
}
// Step 2: Iterate over the map
fmt.Println("Phone Book Listings:")
for name, number := range phoneBook {
// Step 3: Print each key-value pair
fmt.Printf("%s: %s\n", name, number)
}
}
Output:
Phone Book Listings: Alice: 555-1234 Bob: 555-5678 Carol: 555-7890
Explanation:
1. package main - The package declaration for the Go program.
2. import "fmt" - Includes the Format package, which provides I/O functionality.
3. phoneBook is declared and initialized with a map literal containing three key-value pairs, representing a simple phone book.
4. A for range loop iterates over phoneBook. On each iteration, name receives the key and number receives the corresponding value.
5. Inside the loop, fmt.Printf is used to print each name and their associated phone number to the console.
6. The output lists all the entries in the phoneBook map, confirming that the map was successfully iterated over and all key-value pairs were accessed.
Comments
Post a Comment