go - 无法在映射值中使用 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
是否有可能以某种方式使地图接受返回实现接口的结构而不是直接返回该接口的函数?
解决方案
您可以使用简单的匿名函数为您的地图形成兼容的函数签名,而无需更改my_module.New
定义。匿名函数仍在my_module.New
其主体中调用:
constructors["name"] = func New() (core.Module, error) {
return my_module.New()
}
推荐阅读
- json - 如何从 CQL 表中的 JSON 列中选择键作为列?
- java-9 - Java 9 反应式流。为什么需要处理器?
- reporting-services - 根据过滤列过滤/隐藏矩阵中的“空”行
- typescript - d3 在最后一个 x 轴项目上的打字稿填充空间中缩放?
- python - Mosestokenizer 问题:[WinError 2] 系统找不到指定的文件
- c++ - 即使我已经包含了某些标题,也没有找到它们。除了使用引号之外,我该如何解决这个问题?
- liferay-7 - 用自定义替换 top-head.jsp Liferay
- javascript - 在不修改原始数组的情况下将一个数组切片/拼接成另一个数组
- r - 只为一侧设置 Coord_cartesian?
- python - 无法在我的 django 项目中使用多个数据库