【发布时间】:2019-05-18 17:57:07
【问题描述】:
Go 规范指出:
接口类型的变量可以存储任何类型的值,方法集是接口的任何超集。
这样我可以
type Source interface{}
type SourceImpl struct{}
var s Source
g := new(interface{})
s = new(SourceImpl)
*g = s
但是,我不能对地图做同样的事情:
generic := make(map[string]*interface{})
specific := make(map[string]*Source)
generic = specific
给予:
cannot use specific (type map[string]*Source) as type map[string]*interface {} in assignment
这是为什么呢?可以不使用类型断言将特定类型的映射传递/分配给泛型类型的映射吗?
【问题讨论】:
-
问题中的设置与地图中的类型不匹配。设置显示
*Source可以分配给interface{}。为了匹配映射中的类型,设置应该显示*Source可以分配给*interface{}。这是不允许的。无论如何,请参阅第一条评论中链接的常见问题条目。 -
注意
interface{}已经是一个指针类型 -
@ThunderCat 是的,感谢您的提示