golang

Learn How to iterate over a map in Golang


In this article, you are going to learn about how to iterate over a map in the Go language.

Golang provides a built-in associative data type named Map which is basically a collection of key-value pairs. On the map, you can retrieve, delete or update values with the help of keys. It is also known as hash map, hash table, unordered map, or associative array. Let’s see how you can declare a map in the Go language:

var student = map[string]int{
                "Mitchel": 21,
                "Deven":   23,
                "Watson":  32,
                "Jony":    17,
                "Rohit":   19,
        }

This is a demo of declaring a map in Golang. Here, the student map has a collection of key-value pairs where the names of the students are keys and the ages are referred to as values.

You can simply print and see the values of this map but it will not give you total control over it. To get control over a map you need to iterate it. The easiest and widely used way of iterating over a map in Go language is to use for…rang loop. See the below code example:

package main

import "fmt"

func main() {
        var student = map[string]int{
                "Mitchel": 21,
                "Deven":   23,
                "Watson":  32,
                "Jony":    17,
                "Rohit":   19,
        }
        for name, age := range student {
                fmt.Println("Name:", name, "=>", "Age:", age)
        }
}

/*
        Output:
        Name: Deven => Age: 23
        Name: Watson => Age: 32
        Name: Jony => Age: 17
        Name: Rohit => Age: 19
        Name: Mitchel => Age: 21
*/

Here, you can see that names are referred to as a key, and ages are referred to as a value and it prints the values in an unordered manner. This is the way you can iterate over a map in Go language.

You can also print the keys and the values separately. Let’s see a quick example of how you can print only keys. In our case, keys are the name of the students.

for name := range student {
                fmt.Println("Name:", name)
        }

/*
        Output:
        Name: Rohit
        Name: Mitchel
        Name: Deven  
        Name: Watson 
        Name: Jony
*/

let’s see the example of printing values also. In our case, values are the age of the students:

for _, age := range student {
                fmt.Println("Age:", age)
        }

/*
        Output:
        Age: 17
        Age: 19
        Age: 21
        Age: 23
        Age: 32
*/

Here, to avoid the key you have to use the ‘_’ sign otherwise you will get the keys as output instead of getting the values.


Share on social media

//