登录
首页 >  Golang >  Go问答

无法在映射值中使用 my_module.New (type func() (*my_module.MyModule, error)) 作为 type func() (core.Module, error)

来源:stackoverflow

时间:2024-04-18 22:18:34 238浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《无法在映射值中使用 my_module.New (type func() (*my_module.MyModule, error)) 作为 type func() (core.Module, error)》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

在我的程序中,我有一个名为 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

是否可以以某种方式使映射接受返回实现接口的结构的函数,而不是直接返回该接口?


解决方案


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

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

终于介绍完啦!小伙伴们,这篇关于《无法在映射值中使用 my_module.New (type func() (*my_module.MyModule, error)) 作为 type func() (core.Module, error)》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>