Golang ProgramsGolang Programs

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.
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)
    }
}
C:\golang\maps>go run example.go
Key: Rocky => Element: 30
Key: Rajiv => Element: 40
Key: Kate => Element: 50
Key: Mark => Element: 10
Key: Sandy => Element: 20

C:\golang\maps>
Each iteration returns a key and its correlated element value.