go - 带有地图的无效接收器类型
问题描述
我正在尝试在基本地图https://play.golang.org/p/3BKgxVJIjP1上定义其他方法:
type Typ struct {
config string
}
type typeRegistry = map[string]Typ
func (r typeRegistry) Add(name string) {
typ := Typ{
config: "config",
}
r[name] = typ
}
这样做会失败:
invalid receiver type map[string]Typ (map[string]Typ is not a defined type)
在重构之前,该方法是相似的,但使用 afunc
而不是Typ
:
type typeRegistry map[string]func()
func (r typeRegistry) Add(name string, factory func()) {
r[name] = factory
}
这个版本有效。在 map-type 接收器上定义附加方法的区别在哪里?
解决方案
type typeRegistry = map[string]Typ
是一个类型别名。您不能在别名上定义方法(仅在原始类型上 - 但在这种情况下map[string]Typ
不能有方法,所以您不走运)。
您可能想要的是创建自定义类型,而不是别名:
type typeRegistry map[string]Typ
然后你的方法就会奏效。
推荐阅读
- sql - WHERE 代码 SQL 中的多部分标识符错误
- python - ufunc 的循环不支持浮点类型的参数 0,它没有可调用的 exp 方法
- javascript - 搜索过滤器无法过滤我的模拟数据
- python - 如何通过提供名称作为字符串来动态实例化 sklearn 分类器
- swift - CBPeripheral -“didWriteValueFor”得到错误“准备队列已满”。
- r - 如何在 R 中的 Shiny 中应用 actionButton“Upate View”?
- python - 类初始化中的熊猫 set_index 不起作用
- http - 浏览器中包含 HTTP 调用的同步 API?
- vb.net - 打印到另一页而不填满整个前一页
- python - 如何删除 Python-Tkinter def LabelFrame?