【发布时间】:2018-04-07 20:03:29
【问题描述】:
我对 go 中以下语句的合法性有疑问。为什么不能直接转换这两种类型?
package main
import (
"fmt"
)
type xtype interface{}
type ytype map[string]map[string]bool
func main() {
myvar := map[string]xtype{
"x": map[string]interface{}{
"foo": map[string]interface{}{
"bar": true,
},
},
}
x := myvar["x"] // x is of type 'xtype'
fmt.Println(x) // Prints map[foo:map[bar:true]]
y := x.(ytype) // Panic
fmt.Println(y) //
}
这段代码可以编译,但是运行时会出现恐慌
panic: interface conversion: main.xtype is map[string]interface {}, not main.ytype
有人可以解释为什么这是恐慌吗?显然,在这种情况下它们属于同一类型。在 Go 中是否可以进行这种直接转换?
编辑
虽然这是一个人为的例子,但这确实出现在现实世界中。例如,Cloud Firestore(Firebase 的一部分)的 Go 库以 map[string]interface{} 的形式从数据库返回地图,无论它们进入多少层。所以直接转换成目标类型真的很方便
【问题讨论】:
-
见golang.org/doc/faq#convert_slice_of_interface。显然 not 属于同一类型,因为 interface{} 不是 map[string]bool。重复。
标签: go types type-conversion