首页 > 解决方案 > 为什么 map[]interface{} 不采用 map[]SpecificInterface

问题描述

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

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

标签: gointerfacecasting

解决方案


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

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

generic = specific

但是如果你这样做了,当你想使用你的地图时,你需要做一些类型切换或类型断言。


推荐阅读