首页 > 解决方案 > 无法在映射值中使用 my_module.New (type func() (*my_module.MyModule, error)) 作为类型 func() (core.Module, error)

问题描述

在我的程序中,我有一个名为的接口core.Module和一个实现此接口的结构,称为my_module.MyModule. 创建实现我的接口的这些结构的函数被添加到映射中,以便稍后按名称调用它们:

type moduleConstructor func() (core.Module, error)

constructors := make(map[string]moduleConstructor)
constructors["name"] = my_module.New

不幸的是,使这项工作的唯一方法是创建以下New函数:

func New() (core.Module, error) {
} 

我非常喜欢使用推荐的签名:

func New() (*my_module.MyModule, error) {
}

但是,这会导致以下错误:

cannot use my_module.New (type func() (*my_module.MyModule, error)) as type 
func() (core.Module, error) in map value

是否有可能以某种方式使地图接受返回实现接口的结构而不是直接返回该接口的函数?

标签: go

解决方案


您可以使用简单的匿名函数为您的地图形成兼容的函数签名,而无需更改my_module.New定义。匿名函数仍在my_module.New其主体中调用:

constructors["name"] = func New() (core.Module, error) {
    return my_module.New()
} 

推荐阅读