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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?