2017-04-03 72 views
1

在當前項目中,我們通過mgo驅動程序使用Go和MongoDB。 對於每個實體,我們都必須實施用於CRUD操作的DAO,並且它基本上是複製粘貼的,例如,Go和MongoDB:通用DAO實現問題

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沒有泛型,我們如何避免代碼重複?

我試着通過,而不是在方法創建它的result interface{} PARAM,並調用這樣的方法:

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 

然後我試圖使這個PARAM result []interface{},但在這種情況下,它不可能通過[]*entity.User{}

不能使用[] * entity.User文字(輸入[* entity.User)類型[]接口{}在爭論thisDao.GenericDao.FindAll

任何想法,我怎麼可能實現通用DAO在Go?

回答

1

您應該可以將result interface{}傳遞給FindAll函數,並將其傳遞給mgo的Query.All方法,因爲參數的類型相同。

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) 
+0

不,它不起作用。結果:'[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' – dds

+0

看,在你的示例代碼中,你沒有傳遞一個指向片的指針'dao.FindAll( [] * entity.User {})'< - 這就是爲什麼你得到這個錯誤,這不是一個指向切片的指針,它是對用戶結構的一個指向,好嗎?在我的示例中,我添加了一些註釋,指出了這一點......只是在我的示例中測試了代碼,它可以工作。如果您確定要傳遞指向片的指針,請分享更多代碼,以便我可以提供幫助。 – mkopriva

+0

@dds這是它的一個例子http://imgur.com/dbKWJZB – mkopriva