go - 为什么 map[]interface{} 不采用 map[]SpecificInterface

标签 go interface casting

go 规范指出:

A variable of interface type can store a value of any type with a method set that is any superset of the interface.

我可以

type Source interface{}
type SourceImpl struct{}

var s Source
g := new(interface{})
s = new(SourceImpl)

*g = s

但是,我不能与 map 相同:

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

这是为什么呢?是否可以在不使用类型断言的情况下将特定类型的映射传递/分配给泛型类型的映射?

最佳答案

因为 map[]interface{}map[]SpecificInterface 是两种不同的类型。 如果您将泛型类型设为空接口(interface),它就可以工作。

var generic interface{}
specific := make(map[string]*Source)

generic = specific

但如果这样做,当您想要使用 map 时,您需要进行一些类型切换或类型断言。

关于go - 为什么 map[]interface{} 不采用 map[]SpecificInterface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53830945/

相关文章:

go - 如何检查一个go channel是否真的在等待数据?

google-app-engine - go get 失败,返回 "no buildable Go source files found in github.com/..."

go - Go 中的抽象模式

java - 在java中传递后代而不是接口(interface)

c++ - dynamic_cast 还是冗余?

c++ - 如何转换枚举?

go - 为什么这个 Go 程序会挂起?

WPF DataGrid 如何在绑定(bind)到界面时添加空白行

c++ - 在从 void* 转换和返回时混合静态和重新解释转换是否不安全?

go - 如何正确使用 FirstOrCreate