Iterate through the Golang map

I have a map like: map[string]interface{}

And finally, I can 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 over this card? I tried the following:

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

But I get an error message:

 cannot range over mymap typechecking loop involving for loop 

Please, help.

+68
loops go map
Nov 05 2018-11-11T00:
source share
3 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] 
+76
Nov 05 2018-11-11T00:
source share

You can do this one line at a time:

 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) } 

Exit:

 k: foo v: map[first:1] k: boo v: map[second:2] 
+4
Jul 01 '16 at 8:10
source share

You can simply write in multi-line form 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 conclusion:

 $ go run dict.go [ foo ] has items: --> strength : 10 --> age : 2000 [ bar ] has items: --> strength : 20 --> age : 1000 
0
May 20 '19 at 12:14
source share



All Articles