Golang接口简化依赖关系?

huangapple go评论147阅读模式
英文:

Golang interfaces to simplify dependencies?

问题

嗯,我对接口的概念有些困惑。

我正在使用一个处理mongodb的Go包,但我不想在每个模型中都导入该包。我希望尽可能多地使用标准库来管理我的子包(如模型)。所以我想定义一些接口,如下所示:

type m map[string]interface{}

type collectionSlice interface {
    One(interface{}) error
}

type collection interface {
    Upsert(interface{}, interface{}) (interface{}, error)
    Find(interface{}) collectionSlice
}

type database interface {
    C(string) collection
}

问题是,当我尝试使用以下函数时:

func FindItem(defindex int, d database) (*Item, error) {

通过将我的mgo.Database作为参数传递给使用这些接口的包中的函数:

item, err := dota.FindItem(int(defindex), ctx.Database)

我得到一个编译器错误:

controllers/handlers.go:35: cannot use ctx.Database (type *mgo.Database) as type dota.database in function argument:
        *mgo.Database does not implement dota.database (wrong type for C method)
                have C(string) *mgo.Collection
                want C(string) dota.collection

我对这个概念有什么误解吗?

英文:

Hmmm, I'm having a problem wrapping my head around interfaces.

So I am using a Go package for handling my mongodb stuffs, but I don't want to import that package into every model and what not. I'd like to keep as many of my sub packages (like models) to just the standard library. So I thought I would lay out some interfaces like so:

type m map[string]interface{}

type collectionSlice interface {
	One(interface{}) error
}

type collection interface {
	Upsert(interface{}, interface{}) (interface{}, error)
	Find(interface{}) collectionSlice
}

type database interface {
	C(string) collection
}

The problem is, when I go to use a function like:

func FindItem(defindex int, d database) (*Item, error) {

that is found in the package that is using the interfaces by passing in my mgo.Database:

item, err := dota.FindItem(int(defindex), ctx.Database)

I get a compiler error:

controllers/handlers.go:35: cannot use ctx.Database (type *mgo.Database) as type dota.database in function argument:
*mgo.Database does not implement dota.database (wrong type for C method)
have C(string) *mgo.Collection
want C(string) dota.collection

What am I missing about this concept?

答案1

得分: 1

我收到了关于这个回答的回复,来自 golang-nuts。

我遇到的问题是方法必须具有完全相同的签名:
http://golang.org/doc/faq#t_and_equal_interface

感谢 golang-nuts 群组的 Jesse McNelis!

英文:

Got a reply to this answer on golang-nuts.

The issue I'm having is that the methods must have exactly the same signature:
http://golang.org/doc/faq#t_and_equal_interface

Thanks to Jesse McNelis on the golang-nuts group!

huangapple
  • 本文由 发表于 2013年10月27日 12:18:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/19614580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定