Golang Program to Iterate Map Elements using the Range


Maps in Golang provide a convenient way to store and access the given data in format of key−value pairs. Iterating over a map allows us to process each key−value pair and perform operations on them. In this article, we will explore different methods to iterate map elements using the range, that includes using the range keyword, using keys and values slices, and using the reflect package.

Syntax

for key, value := range mapName {
    // Perform operations on key-value pair
}

This syntax uses the range keyword to iterate over the elements of the map mapName. In each iteration, the key and value variables are assigned to the corresponding key−value pair. You can perform operations on the key−value pair inside the loop.

reflect.ValueOf(mapName)

By using this syntax we retrieve the reflect.Value of the map

MapKeys() 

It returns a slice containing all its keys.

MapIndex(key)

It allows fetching the corresponding value for each key

Interface()

It is used to convert the reflect.Value to its actual value.

Algorithm

  • Iterate over the elements of the map using the range keyword:

  • For each iteration, assign the key to the variable 'key' and the value to the variable 'value'.

  • Perform operations on the key−value pair as required.

Example

In this example we can perform operations on the key−value pair within the loop. Let us Consider a map studentScores that stores the names of students as keys and their corresponding scores as values. We will iterate over this map using the range keyword and print each student's name and score.

package main

import "fmt"

func main() {
    studentScores := map[string]int{
        "John":   85,
        "Alice":  90,
        "Bob":    75,
        "Sara":   95,
        "Michael": 80,
    }


    for name, score := range studentScores {
        fmt.Printf("Student: %s, Score: %d\n", name, score)
    }
}

Output

Student: Alice, Score: 90
Student: Bob, Score: 75
Student: Sara, Score: 95
Student: Michael, Score: 80
Student: John, Score: 85

Example

In this example we start by creating slices 'keys' and 'values' of appropriate types and initialising an index 'i' as 0. We then iterate over the map elements and assign each key and value to the corresponding slice at index 'i'. Let us consider a map fruitStock that stores the names of fruits as keys and their corresponding stock quantities as values. We will iterate over this map using the keys and values slices method and print the fruits and their stock quantities.

package main

import "fmt"

func main() {
    fruitStock := map[string]int{
        "apple":   10,
        "banana":  20,
        "orange":  15,
        "mango":   8,
        "pineapple": 12,
    }

    keys := make([]string, len(fruitStock))
    values := make([]int, len(fruitStock))
    i := 0
    for fruit, stock := range fruitStock {
        keys[i] = fruit
        values[i] = stock
        i++
    }

    for i := 0; i < len(keys); i++ {
        fmt.Printf("Fruit: %s, Stock: %d\n", keys[i], values[i])
    }
}

Output

Fruit: apple, Stock: 10
Fruit: banana, Stock: 20
Fruit: orange, Stock: 15
Fruit: mango, Stock: 8
Fruit: pineapple, Stock: 12

Example

In this example we are going to use the reflect package to obtain the “reflect.Value” of the map. We then retrieve the keys using 'mapValue.MapKeys()' and iterate over them using the range keyword. Let us Consider a map “employeeSalaries” that stores the names of employees as keys and their corresponding salaries as values. We will iterate over this map using the reflect package method and print each employee's name and salary.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    employeeSalaries := map[string]int{
        "John":    50000,
        "Alice":   60000,
        "Bob":     55000,
        "Sara":    65000,
        "Michael": 70000,
    }

    mapValue := reflect.ValueOf(employeeSalaries)
    mapKeys := mapValue.MapKeys()

    for _, key := range mapKeys {
        value := mapValue.MapIndex(key).Interface()
        fmt.Printf("Employee: %s, Salary: %d\n", key.String(), value.(int))
    }
}

Output

Employee: John, Salary: 50000
Employee: Alice, Salary: 60000
Employee: Bob, Salary: 55000
Employee: Sara, Salary: 65000
Employee: Michael, Salary: 70000

Real life implementations

Employee Payroll Processing

Imagine you're working on a payroll processing system for a company. You have a map that contains the names of employees as keys and their corresponding salaries as values. You need to calculate bonuses for employees based on their salaries.

By iterating over the map using the range keyword, you can efficiently calculate and apply bonuses to each employee's salary. This allows you to process payroll data accurately and make adjustments to individual employee compensation.

E−commerce Order Tracking

Suppose you're developing an order tracking system for an e−commerce platform. You have a map that stores order IDs as keys and their corresponding delivery statuses as values. You need to update the delivery status of each order as they are shipped and delivered.

iterate map elements using the range keyword enables you to quickly update the delivery status of each order. As new orders are processed and shipped, you can easily mark their statuses as "shipped" and "delivered" without affecting other orders' statuses.

Conclusion

In this article we have looked at how we can iterate map elements using the range in go language. Here we use three methods. The range keyword provides a simple and concise way to iterate over a map. Using keys and values, slices allows for more flexibility in handling keys and values separately. The reflect package provides a dynamic approach to iterate over map elements, although it may have some performance implications.

Updated on: 07-Sep-2023

142 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements