2 回答

TA貢獻1808條經驗 獲得超4個贊
該函數采用參數,因此您必須傳遞 .由于這兩種結構都嵌入在其中,因此您可以執行以下操作:processWolfWolfWolfWolf
processWolf(porthos.Wolf)
processWolf(aussie.Wolf)
因為當你嵌入到 ,得到所有的方法都有,加上有一個名為 的成員。WolfDogDogWolfDogWolf

TA貢獻1871條經驗 獲得超8個贊
當我最初發布問題時,我試圖簡化問題陳述,也許太多了,Serdar先生很好心地回答了這個問題,但沒有幫助我的問題。在深入研究了gophers的lang之后,我遇到了一個使用interface{}來解決這個問題的解決方案。我改編了我的mongo代碼,它正在工作,盡管我可能會說它看起來不像其他語言傳遞引用那么簡單。
// FindAll retrieves one object from the collection
func FindAll(collection *mongo.Collection, filter bson.M, resultSet interface{}) error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Seconds)
defer cancel()
cursor, err := collection.Find(ctx, filter)
if err != nil {
return err
}
defer cursor.Close(ctx)
objects := reflect.ValueOf(resultSet).Elem()
for cursor.Next(ctx) {
obj := reflect.New(objects.Type().Elem())
err = cursor.Decode(obj.Interface())
if err != nil {
log.Panicln("FindAll:", err.Error())
// assuming that an interface is out of alignment and need to know ASAP.
}
objects = reflect.Append(objects, obj.Elem())
}
reflect.ValueOf(resultSet).Elem().Set(objects)
return nil
}
然后調用它使用
var dogs []Dog
if err := database.FindAll(houseCollection, bson.M{}, &dogs); err != nil {
return nil, err
}
println(dogs)
var dingos []Dingo
if err := database.FindAll(houseCollection, bson.M{}, &dingos); err != nil {
return nil, err
}
println(dingos)
沒有狗和野狗必須與基類相關。但我真的覺得Golang的設計師做了一些奇怪的轉折,我還沒有理解。雖然有樂趣追逐地鼠。
- 2 回答
- 0 關注
- 115 瀏覽
添加回答
舉報