首页 > 解决方案 > 带有地图的无效接收器类型

问题描述

我正在尝试在基本地图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 接收器上定义附加方法的区别在哪里?

标签: go

解决方案


type typeRegistry = map[string]Typ

是一个类型别名。您不能在别名上定义方法(仅在原始类型上 - 但在这种情况下map[string]Typ不能有方法,所以您不走运)。

您可能想要的是创建自定义类型,而不是别名:

type typeRegistry map[string]Typ

然后你的方法就会奏效。


推荐阅读