go - 为什么 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
这是为什么?可以在不使用类型断言的情况下将特定类型的映射传递/分配给泛型类型的映射吗?
解决方案
因为map[]interface{}
和map[]SpecificInterface
是两种不同的类型。如果您将泛型类型设为空接口,则它可以工作。
var generic interface{}
specific := make(map[string]*Source)
generic = specific
但是如果你这样做了,当你想使用你的地图时,你需要做一些类型切换或类型断言。
推荐阅读
- c# - 如何更新输入的 Datalist 而不会失去对 Blazor 中输入的关注?
- c - C(rand函数)中如何生成随机数?
- c - 如何将输入写入二进制文件并在c中读取?
- c++ - 这是 C 代码中“strcmp”替代品的可用解决方案吗?
- reactjs - 对 State 进行搜索以过滤结果 react native
- c - C中的增量操作:一个表达式中的双倍增量(C89)
- haskell - 多个文件使用相同的模块名称:
- mysql - Rails - Mysql2::Error: MySQL 客户端未连接:ROLLBACK
- r - Rstudio 无法打开或保存脚本
- caddy - Caddy 处理子目录 api