How to iterate over a map in Go?

A map is an unordered collection of key/value pairs, where each key is unique. Go Range keyword is used in different kinds of data structures in order to iterate over elements.

Example 1: Iterate over all keys and values

// Go program to illustrate how
// to iterate the map
package main

import "fmt"

// Main function
func main() {

// Let’s define a map first
usermap := map[string]string{

"North America": "Adam",
"Asia": "Yusuke",
"Africa": "Arif",
"South America": "Rahul",
"Australia": "Joy",
"Europe": "Roman",
"Antarctica": "Penguin",
}

// Iterating over all keys and values
for id, name := range usermap {

fmt.Printf("id :%s name: %s\n", id, name)
}
}

Output:



Example 2: Iterate over all keys

// Go program to illustrate how
// to iterate the map
package main

import "fmt"

// Main function
func main() {

// Let’s define a map first
usermap := map[string]string{

"North America": "Adam",
"Asia": "Yusuke",
"Africa": "Arif",
"South America": "Rahul",
"Australia": "Joy",
"Europe": "Roman",
"Antarctica": "Penguin",
}

// Iterating over all keys
for id := range usermap {

fmt.Printf("id :%s\n", id)
}
}

Output:



Example 3: Iterate over all values

// Go program to illustrate how
// to iterate the map
package main

import "fmt"

// Main function
func main() {

// Let’s define a map first
usermap := map[string]string{

"North America": "Adam",
"Asia": "Yusuke",
"Africa": "Arif",
"South America": "Rahul",
"Australia": "Joy",
"Europe": "Roman",
"Antarctica": "Penguin",
}

// Iterating over all values
for _, name := range usermap {

fmt.Printf("name :%s\n", name)
}
}

Output:

                                            
                                        Author name,
                                                                                Seril

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example