How to iterate through map in Golang?

by anahi.murazik , in category: Golang , 2 years ago

How to iterate through map in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@anahi.murazik you can use range to iterate through any map in Golang, code:


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

import "fmt"

func main() {

   var cars = map[int]string{
      1: "BMW",
      2: "Chevrolet",
      3: "Honda",
   }
   for key, car := range cars {
      fmt.Println("Index:", key, "Value:", car)
   }
   // Output:
   // Index: 1 Value: BMW
   // Index: 2 Value: Chevrolet
   // Index: 3 Value: Honda
}

Member

by wiley , 9 months ago

@anahi.murazik 

In Go, iterating through a map can be done using the for range loop. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func main() {
    m := make(map[string]int)
    m["apple"] = 1
    m["banana"] = 2
    m["cherry"] = 3

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


In the code above, we create a map m with key-value pairs representing fruits and their corresponding numbers. Using the for range loop, we iterate through the map and print each key and value using the fmt.Println() function. The output will be:

1
2
3
apple 1
banana 2
cherry 3


The order of iteration is not guaranteed in a map, as the maps are implemented as unordered collections.