How to iterate over a Map in Golang

  • 16 November 2020
  • ADM

 

How to iterate over a Map in Golang - images/logos/golang.jpg

 

To interate over a map in Golang it van be used the for...each loop statement.

Golang map iterate example

package main
 
import "fmt"
 
func main() {
	fmt.Println("Map iterate example in Golang")
	fmt.Println()
    var shoppingList = map[string]string{
		"Name": "Deidre Haider", 
		"Address": "631 Grand Avenue Glendora, CA 91740",
		"Phone": "202-555-0150",
		"Email": "deidre.haider@example.com"}
    for key, element := range shoppingList {
        fmt.Println("Key:", key, "=>", "Element:", element)
    }
}

Output

For each iteration you can access the key and its correlated element value.

Map iterate example in Golang

Key: Name => Element: Deidre Haider
Key: Address => Element: 631 Grand Avenue Glendora, CA 91740
Key: Phone => Element: 202-555-0150
Key: Email => Element: deidre.haider@example.com

 

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build example.go

Assuming that example.go is the name of your file.

Then depending on if you are on Linux or Windows the binary file is created.

To run the application, execute the command.

Linux

$ ./example

Windows

c:\Users\adm\go\tutorials> example.exe

If you want to compile and run the application in one single step, run the following command:

go run example.go

 

References