Go - Map Loop Example

In this example, we show how to loop over a Map in Go with an example.

With for and range keywords, we can loop over map elements.

Go - Map loop example

In the below example, we loop over countries map in two ways.

package main

import "fmt"

func main() {

    countries := map[string]string{
        "IN": "India",
        "NP": "Nepal",
        "TR": "Turkey",
        "JP": "Japan",
        "ZW": "Zimbabwe",
    }

    for country := range countries {
        fmt.Println(country, "=>", countries[country])
    }

    for key, value := range countries {
        fmt.Printf("countries[%s] = %s\n", key, value)
    }
}

Output:

IN => India
NP => Nepal
TR => Turkey
JP => Japan
ZW => Zimbabwe
countries[JP] = Japan
countries[ZW] = Zimbabwe
countries[IN] = India
countries[NP] = Nepal
countries[TR] = Turkey

In the first case, we loop by pair objects:

package main

import "fmt"

func main() {

    countries := map[string]string{
        "IN": "India",
        "NP": "Nepal",
        "TR": "Turkey",
        "JP": "Japan",
        "ZW": "Zimbabwe",
    }

    for country := range countries {
        fmt.Println(country, "=>", countries[country])
    }
}

In the second case, we loop by keys and values:

package main

import "fmt"

func main() {

    countries := map[string]string{
        "IN": "India",
        "NP": "Nepal",
        "TR": "Turkey",
        "JP": "Japan",
        "ZW": "Zimbabwe",
    }

   for key, value := range countries {
      fmt.Printf("countries[%s] = %s\n", key, value)
   }
}


Comments