繁体   English   中英

golang:恐慌:接口转换:接口{}是地图[字符串]接口{} [重复]

[英]golang: panic: interface conversion: interface {} is map[string]interface {} [duplicate]

我很困惑为什么这段代码会失败。

// This fails with
// panic: interface conversion: interface {} is map[string]interface {}, not main.MyType
// def := (abc.(MyType))["def"]

// But this succeeds
def := (abc.(map[string]interface{}))["def"]

我的想法是在上述逻辑中强制执行的类型断言也应该有效。 有人可以澄清一下吗?

这是整个代码,也是在playground上。

提前致谢。

func foo() {
    type MyType map[string]interface{}

    str := `{
        "abc": {
          "def": {
            "mln": true
          }
        }
      }`
    var data MyType
    if err := json.Unmarshal([]byte(str), &data); err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(data)

    abc := data["abc"]
    fmt.Println(abc)

    // This fails with
    // panic: interface conversion: interface {} is map[string]interface {}, not main.MyType
    // def := (abc.(MyType))["def"]

    // But this succeeds
    def := (abc.(map[string]interface{}))["def"]

    fmt.Println(def)
}

类型断言测试对象的声明类型。 在这段代码中, abcMyType类型,但abc中的嵌套对象是map[string]interface{}实例。 因此,您不能将其类型断言为MyType ,但您可以将其转换:

def := MyType(abc["def"].(map[string]interface{}))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM