关于golang接口循环

时间:2016-04-18 15:05:51

标签: loops go interface

我想打印一个复杂的数据集,如下面的

package main
import (
    "fmt"
    // "reflect"
)

func main() {

    var initData []interface{}
    initData[0] = map[string]interface{}{
        "name": "k1",
        "type": "line",
        "data": []int{1, 2, 3, 4},
    }

    initData[1] = map[string]interface{}{
        "name": "k2",
        "type": "circle",
        "data": []int{11, 12, 13, 14},
    }

    for _, data := range initData {
        for k, v := range data {
            fmt.Println(k)
            for _, sv := range v {
                fmt.Println("  " + sv)
            }
        }

    }

}

但收到错误

./maps-in-maps.go:56: cannot range over data (type interface {})

任何帮助?尝试将界面类型化数据集与arry或slice

等可整合对齐

1 个答案:

答案 0 :(得分:4)

您必须首先键入断言每个interface{}级别,在这种情况下,在map[string]interface{}级别使用类型断言,因为我们知道明确的类型,并且键入开关以检查下一级别中每个嵌套值的预期类型。

initData := []interface{}{
        map[string]interface{}{
            "name": "k1",
            "type": "line",
            "data": []int{1, 2, 3, 4},
        },

        map[string]interface{}{
            "name": "k2",
            "type": "circle",
            "data": []int{11, 12, 13, 14},
        },
    }

    for _, data := range initData {
        for _, v := range data.(map[string]interface{}) {
            switch t := v.(type) {
            case string, []int:
                fmt.Println(t)
            default:
                fmt.Println("wrong type")           
            }
        }
    }
}

运行playground here