dongnue4923 2018-04-28 03:53
浏览 47
已采纳

如何在Go中模拟MongoDB中添加克隆和复制功能?

I read this article and it has good guides for mocking MongoDB in Go. But there are some problems in Clone() and Copy() methods. I create this interfaces and structs:

type ISession interface {
    DB(name string) IDatabase
    Close()
    Clone() ISession
    Copy() ISession
}

type IDatabase interface {
    C(name string) ICollection
}

type MongoSession struct {
    dbSession *mgo.Session
}

func (s MongoSession) DB(name string) IDatabase {
    return &MongoDatabase{Database: s.dbSession.DB(name)}
}

func (s MongoSession) Clone() ISession {
    //return session.clone
    return s.dbSession.Clone()
}

func (s MongoSession) Copy() ISession {
    return s.dbSession.Copy()
}

But I got this error

cannot use s.dbSession.Clone() (type *mgo.Session) as type ISession in return argument: *mgo.Session does not implement ISession (wrong type for Clone method) have Clone() *mgo.Session want Clone() ISession

cannot use s.dbSession.Copy() (type *mgo.Session) as type ISession in return argument: *mgo.Session does not implement ISession (wrong type for Clone method) have Clone() *mgo.Session want Clone() ISession

How can I add Clone() and Copy() methods to interface?

  • 写回答

1条回答 默认 最新

  • doushun1904 2018-04-28 07:18
    关注

    MongoSession.Copy() and MongoSession.Clone() must return a value that implements ISession. Basically you create MongoSession type exactly for this: to implement ISession.

    mgo.Session does not implement your ISession interface (e.g. because its Session.Clone() method has a return type of *mgo.Session and not ISession). You should create and return a new value of MongoSession, in which you can wrap the copied or cloned *mgo.Session value.

    Like this:

    func (s MongoSession) Clone() ISession {
        return MongoSession{dbSession: s.dbSession.Clone()}
    }
    
    func (s MongoSession) Copy() ISession {
        return MongoSession{dbSession: s.dbSession.Copy()}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!