Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through a golang map

Tags:

loops

go

map

I have a map of type: map[string]interface{}

And finally, I get to create something like (after deserializing from a yml file using goyaml)

mymap = map[foo:map[first: 1] boo: map[second: 2]] 

How can I iterate through this map? I tried the following:

for k, v := range mymap{ ... } 

But I get an error:

cannot range over mymap typechecking loop involving for loop 

Please help.

like image 440
ashokgelal Avatar asked Nov 05 '11 07:11

ashokgelal


People also ask

Can you iterate through a map in Golang?

As a Golang map is an unordered collection, it does not preserve the order of keys. We can use additional data structures to iterate over these maps in sorted order.

How do you iterate an array in Golang?

Explanation: The variable i is initialized as 0 and is defined to increase at every iteration until it reaches the value of the length of the array. Then the print command is given to print the elements at each index of the array one by one.

Is map sorted in Golang?

By default Golang prints the map with sorted keys but while iterating over a map, it follows the order of the keys appearing as it is.

How do you check if a key exists in a map Golang?

To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.


1 Answers

For example,

package main  import "fmt"  func main() {     type Map1 map[string]interface{}     type Map2 map[string]int     m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}     //m = map[foo:map[first: 1] boo: map[second: 2]]     fmt.Println("m:", m)     for k, v := range m {         fmt.Println("k:", k, "v:", v)     } } 

Output:

m: map[boo:map[second:2] foo:map[first:1]] k: boo v: map[second:2] k: foo v: map[first:1] 
like image 91
peterSO Avatar answered Sep 19 '22 03:09

peterSO