Go和MongoDB:通用DAO实现问题
在当前项目中,我们通过mgo驱动程序使用Go和MongoDB。 对于每个实体,我们必须为CRUD操作实现DAO,它基本上是复制粘贴,例如Go和MongoDB:通用DAO实现问题,mongodb,go,dao,mgo,Mongodb,Go,Dao,Mgo,在当前项目中,我们通过mgo驱动程序使用Go和MongoDB。 对于每个实体,我们必须为CRUD操作实现DAO,它基本上是复制粘贴,例如 func (thisDao ClusterDao) FindAll() ([]*entity.User, error) { session, collection := thisDao.getCollection() defer session.Close() result := []*entity.User{} //create a
func (thisDao ClusterDao) FindAll() ([]*entity.User, error) {
session, collection := thisDao.getCollection()
defer session.Close()
result := []*entity.User{} //create a new empty slice to return
q := bson.M{}
err := collection.Find(q).All(&result)
return result, err
}
对于其他所有实体,除了结果类型之外,其他所有实体都是相同的
既然Go没有泛型,我们如何避免代码重复
我尝试传递结果接口{}
参数,而不是在方法中创建它,并像这样调用该方法:
dao.FindAll([]*entity.User{})
但是collection.Find().All()
方法需要一个切片作为输入,而不仅仅是接口:
[restful] recover from panic situation: - result argument must be a slice address
/usr/local/go/src/runtime/asm_amd64.s:514
/usr/local/go/src/runtime/panic.go:489
/home/dds/gopath/src/gopkg.in/mgo.v2/session.go:3791
/home/dds/gopath/src/gopkg.in/mgo.v2/session.go:3818
然后我尝试使这个参数result[]接口{}
,但在这种情况下,无法传递[]*实体。用户{}
:
无法在thisDao.GenericDao.FindAll的参数中将[]*entity.User literal(type[]*entity.User)用作类型[]接口{}
你知道如何在Go中实现泛型DAO吗?你应该能够将
结果接口{}
传递给你的FindAll
函数,并将其传递给mgo的方法,因为参数的类型相同
func (thisDao ClusterDao) FindAll(result interface{}) error {
session, collection := thisDao.getCollection()
defer session.Close()
q := bson.M{}
// just pass result as is, don't do & here
// because that would be a pointer to the interface not
// to the underlying slice, which mgo probably doesn't like
return collection.Find(q).All(result)
}
// ...
users := []*entity.User{}
if err := dao.FindAll(&users); err != nil { // pass pointer to slice here
panic(err)
}
log.Println(users)
不,它不起作用。结果:
[restful]从恐慌状态恢复:-结果参数必须是片地址/usr/local/go/src/runtime/asm_amd64.s:514/usr/local/go/src/runtime/panic.go:489/home/dds/gopath/src/gopkg.in/mgo.v2/session.go:3791*entity.User{}