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

我读了这个
article,它有很好的指导,用于在Go中模拟MongoDB.但是Clone()和Copy()方法存在一些问题.

我创建了这个接口和结构:

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()
}

但我得到了这个错误

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

如何将Clone()和Copy()方法添加到接口?

最佳答案 MongoSession.Copy()和MongoSession.Clone()必须返回一个实现ISession的值.基本上你完全为此创建MongoSession类型:实现ISession.

mgo.Session没有实现您的ISession接口(例如,因为其Session.Clone()方法的返回类型为* mgo.Session而不是ISession).您应该创建并返回MongoSession的新值,您可以在其中包装复制或克隆的* mgo.Session值.

像这样:

func (s MongoSession) Clone() ISession {
    return MongoSession{dbSession: s.dbSession.Clone()}
}

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