How to loop through a map in golang?

Member

by emely , in category: Golang , 2 years ago

How to loop through a map in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@emely you can use for loop to iterate over any map in Golang, the code would be something like this:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
package main

import (
   "fmt"
)

func main() {
   mapExample := map[int]string{0: "john", 1: "steven"}
   // Output: map: map[0:john 1:steven]
   fmt.Println("map:", mapExample)
   for key, value := range mapExample {
      fmt.Println("key:", key, "value:", value)
   }
   // Output:
   //key: 0 value: john
   //key: 1 value: steven
}

Member

by anthony , a year ago

@emely 

To loop through a map in Golang, you can use a for loop with the range keyword. Here's an example:

1
2
3
4
5
m := map[string]int{"apple": 1, "banana": 2, "orange": 3}

for key, value := range m {
    fmt.Println(key, value)
}


This code will output:

1
2
3
apple 1
banana 2
orange 3


The range keyword returns both the key and the value of each pair in the map. You can use these variables in your loop to perform any calculations necessary.