114

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.

1
  • Is it possible to provide a test case? It's hard to diagnose the problem from what you've posted, since there's nothing inherent to what you've posted that could cause a type checking loop. In particular, I'm having trouble figuring out how you'd get a type checking loop in a function body. Nov 6, 2011 at 5:18

3 Answers 3

131

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]
5

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                },
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
                },
        }
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)
                }

        }
}

And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000
2
  • thank you. what would call the portion of the code value.(map[string]int)? is that called "coercing value to a new type" in Go? (new to Go)
    – 123
    Feb 3, 2022 at 8:33
  • 1
    @123 I think, type assertion go.dev/tour/methods/15
    – han solo
    Mar 4, 2022 at 12:43
3

You can make it by one line:

mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
    fmt.Println("k:", k, "v:", v)
}

Output is:

k: foo v: map[first:1]
k: boo v: map[second:2]
1
  • 26
    Go Proverb: Don't be clever, be explicit. One-liners are not the goal in Go. Feb 23, 2019 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.