Go Program to Iterate Over a Map

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

  1. Import the fmt Package: Use import "fmt" for formatted I/O operations.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Create and Initialize the Map: Use a map literal to create and initialize a map with some key-value pairs.
  4. Iterate Over the Map: Use a for loop with the range keyword to iterate over the map.
  5. Display Each Key-Value Pair: Use fmt.Println to 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 for loop with the range keyword is used to iterate over the map. The loop iterates over each key-value pair in the map. The variable key holds the key, and the variable value holds the corresponding value.

Step 3: Display Each Key-Value Pair

  • Inside the loop, fmt.Println is used to print each key-value pair in the format key: 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top