2
所以我想要有一个函数名称的映射来选择基于环境变量的接口的实现。我在下面的代码复制它:创建构造函数的地图
package test
type Fooer interface {
Foo() error
}
type Bar struct{}
func NewBar() (*Bar, error) { return &Bar{}, nil }
func (b *Bar) Foo() error { return nil }
type Baz struct{}
func NewBaz() (*Baz, error) { return &Baz{}, nil }
func (b *Baz) Foo() error { return nil }
var constructors map[string]func() (*Fooer, error)
func init() {
constructors = map[string]func() (*Fooer, error){
"bar": NewBar,
"baz": NewBaz,
}
}
这将引发以下错误,当我go build test.go
:
./test.go:21: cannot use NewBar (type func() (*Bar, error)) as type func() (*Fooer, error) in map value
./test.go:22: cannot use NewBaz (type func() (*Baz, error)) as type func() (*Fooer, error) in map value
那我做错了吗?我可以使用*Fooer
作为构造函数的返回类型吗? 实际什么是最好的方法来解决这个问题? (我是新来的GO)
重新3:只是一次,而我设置服务器的配置。需要选择使用哪个存储实施。 –
另外,我修改它不返回一个指针,我得到相同的错误(模块指针,显然。)我错过了什么? –
比一个简单的'var storage Fooer;如果init中的environmentWantsBaz {storage,_ = Baz {}} else {storage,_ = Bar {}}'应该这样做。 – Volker