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

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example