douxingmou4533 2013-10-27 04:18
浏览 51
已采纳

Golang接口可以简化依赖关系?

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条回答 默认 最新

  • dongping4461 2013-10-27 04:29
    关注

    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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line