0
0
Goprogramming~5 mins

Iterating over maps in Go

Choose your learning style9 modes available
Introduction

We use iteration to look at each item in a map one by one. This helps us work with all the data stored in the map.

When you want to print all keys and values in a map.
When you need to find a specific value by checking each item.
When you want to change or use every value in the map.
When you want to count or summarize data stored in a map.
Syntax
Go
for key, value := range mapName {
    // use key and value here
}

The range keyword helps go through each item in the map.

You get both the key and value for each item during the loop.

Examples
This prints each key and value in the map.
Go
for k, v := range myMap {
    fmt.Println(k, v)
}
This prints only the keys, ignoring the values.
Go
for k := range myMap {
    fmt.Println(k)
}
This prints only the values, ignoring the keys.
Go
for _, v := range myMap {
    fmt.Println(v)
}
Sample Program

This program creates a map of fruit codes to fruit names. It then loops over the map and prints each key and its value.

Go
package main

import "fmt"

func main() {
    fruits := map[string]string{
        "a": "Apple",
        "b": "Banana",
        "c": "Cherry",
    }

    for key, value := range fruits {
        fmt.Printf("Key: %s, Value: %s\n", key, value)
    }
}
OutputSuccess
Important Notes

The order of items when iterating over a map is random each time.

You can ignore the key or value by using an underscore _ if you don't need it.

Summary

Use for key, value := range map to look at all items in a map.

You get both keys and values during the loop.

The order of items is not fixed, so don't rely on it.