Iterating through a golang map

ashokgelal picture ashokgelal · Nov 5, 2011 · Viewed 97.2k times · Source

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.

Answer

peterSO picture peterSO · Nov 5, 2011

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]