How to iterate over a Map using for loop in Go?


The for…range loop statement can be used to fetch the index and element of a map.

Example

package main

import "fmt"

func main() {
    var employee = map[string]int{"Mark": 10, "Sandy": 20,
        "Rocky": 30, "Rajiv": 40, "Kate": 50}
    for key, element := range employee {
        fmt.Println("Key:", key, "=>", "Element:", element)
    }
}

Output

Key: Rocky => Element: 30
Key: Rajiv => Element: 40
Key: Kate => Element: 50
Key: Mark => Element: 10
Key: Sandy => Element: 20
Each iteration returns a key and its correlated element value.
Most Helpful This Week