遍历golang映射


89

我有一个类型的地图: 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

请帮忙。


是否可以提供测试用例?很难根据您发布的内容来诊断问题,因为您发布的内容没有内在的隐患,不会导致类型检查循环。特别是,我在弄清楚如何在函数体中进行类型检查循环时遇到麻烦。
SteveMcQwark

Answers:


107

例如,

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]

4

您可以一行完成:

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]

20
谚语:不要聪明,要明确。单行不是Go中的目标。
伊南克·古姆斯

2

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

$ 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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.