In my program I have an interface called core.Module
and a struct which implements this interface called my_module.MyModule
. Functions creating those structs implementing my interface are added to a map in order to call them by name later:
type moduleConstructor func() (core.Module, error)
constructors := make(map[string]moduleConstructor)
constructors["name"] = my_module.New
Unfortunately the only way to make this work is to create a following New
function:
func New() (core.Module, error) {
}
I would very much prefer to use a recommended signature:
func New() (*my_module.MyModule, error) {
}
However that causes the following error:
cannot use my_module.New (type func() (*my_module.MyModule, error)) as type
func() (core.Module, error) in map value
Is it possible to somehow make the map accept functions which return structs implementing an interface instead of directly returning that interface?
You can use a simple anonymous function to form compliant function signature for your map without changing my_module.New
definition. The anonymous function still call my_module.New
in its body:
constructors["name"] = func New() (core.Module, error) {
return my_module.New()
}