通过golang地图迭代

时间:2011-11-05 07:03:39

标签: map go loops

我有一张类型为map[string]interface{}

的地图

最后,我开始创建类似的东西(在使用goyaml从yml文件反序列化之后)

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

如何迭代这张地图?我尝试了以下方法:

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

但是我收到了一个错误:

cannot range over mymap
typechecking loop involving for loop

请帮忙。

3 个答案:

答案 0 :(得分:76)

例如,

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

输出:

m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]

答案 1 :(得分:5)

你可以用一行来制作它:

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

输出是:

k: foo v: map[first:1]
k: boo v: map[second:2]

答案 2 :(得分:0)

您可以像这样在多行中写出来,

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

        }
}

输出:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000