我试图在基本地图上定义其他方法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
}
Run Code Online (Sandbox Code Playgroud)
这样做会失败:
invalid receiver type map[string]Typ (map[string]Typ is not a defined type)
Run Code Online (Sandbox Code Playgroud)
重构之前,方法类似,但用 afunc代替Typ:
invalid receiver type map[string]Typ (map[string]Typ is not a defined type)
Run Code Online (Sandbox Code Playgroud)
这个版本有效。在映射类型接收器上定义附加方法的区别在哪里?
type typeRegistry = map[string]Typ
Run Code Online (Sandbox Code Playgroud)
是一个类型别名。您不能在别名上定义方法(只能在原始类型上定义方法,但在这种情况下map[string]Typ不能在别名上定义方法,所以您运气不好)。
您可能想要的是创建自定义类型,而不是别名:
type typeRegistry map[string]Typ
Run Code Online (Sandbox Code Playgroud)
那么你的方法就会起作用。
| 归档时间: |
|
| 查看次数: |
1603 次 |
| 最近记录: |