dougu7546 2013-12-10 12:22
浏览 40
已采纳

创建构造函数图

So I'd like to have a map of names of functions, to choose an implementation of an interface based on an environment variable. I've reproduced it in the following code:

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,
    }
}

This throws the following errors when I 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

So what am I doing wrong? Can I use a *Fooer as the return type of a constructor function? What would be the actual best way to approach this? (I'm new to Go)

  • 写回答

1条回答 默认 最新

  • duanqu9292 2013-12-10 12:43
    关注
    1. Do not (almost never) pass around pointers to interface. You will (almost) never need a *Fooer, a Fooer is enough.
    2. Yes, your Bar and Baz constructors could return a Fooer (not a *Fooer!) but that seems awkward.
    3. Keeping the constructors in a map and querying the map for a constructor seem like one level of indirection too much. Are you constantly creating new Bar and Baz?
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么