我需要定义这些接口来模拟官方mongo驱动程序
type MgCollection interface {
FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *mongo.SingleResult
// Other methods
}
type MgDatabase interface {
Collection(name string, opts ...*options.CollectionOptions) MgCollection
// Other methods
}
在Mongo驱动程序包中,有两个结构体mongo.Collection和mongo.Database,拥有以下方法。
func (coll *Collection) FindOne(ctx context.Context, filter interface{}, opts ...*options.FindOneOptions) *SingleResult {
// Method code
}
func (db *Database) Collection(name string, opts ...*options.CollectionOptions) *Collection {
// Method code
}
结构体 *mongo.Collection 正确实现了 MgCollection,因此此代码可以编译通过。
var col mgdriver.MgCollection
col = &mongo.Collection{}
col.FindOne(ctx, nil, nil)
但是结构体 *mongo.Database 没有实现 MgDatabase,所以当我编写如下内容时:
var db mgdriver.MgDatabase
db = &mongo.Database{}
db.Collection("Test", nil)
编译器显示以下错误:
无法使用 &mongo.Database 字面值(类型为 *mongo.Database)作为 mgdriver.MgDatabase 的类型进行赋值: *mongo.Database 不实现 mgdriver.MgDatabase(Collection 方法的类型不正确), 拥有 Collection(string, ...*options.CollectionOptions) *mongo.Collection 需要 Collection(string, ...*options.CollectionOptions) mgdriver.MgCollection mongo.Collection 和 mongo.Database 都是官方软件包中的内容,我不能更改该软件包中的任何代码。那么如何更改我的接口以正确地模拟官方的 mongo driver?
import github.com/globalsign/mgo/dbtest
。或者按照建议稍微复制一下。 - Markus W Mahlberg