亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

清空接口類型斷言并創建副本

清空接口類型斷言并創建副本

Go
元芳怎么了 2023-07-10 09:26:00
無法弄清楚如何修改作為指針傳遞給接受空接口的函數的結構類型變量我正在創建一種通過官方 go 驅動程序與 MongoDB 數據庫配合使用的庫。我傳遞一個結構指針,然后用數據庫(MongoDB)中的數據填充該指針cursor.Decode。這對于單個文檔來說效果很好,但是當我嘗試返回文檔數組時,只有父文檔是正確的,但子文檔(嵌入的)對于數組中的所有元素保持不變(可能存儲引用而不是實際值)。實際代碼:// passing model pointer to search functionresult, _ := mongodb.Search(&store.Time{},                 mongodb.D{mongodb.E("transdate",                     mongodb.D{mongodb.E("$gte", timeSearch.DateFrom), mongodb.E("$lte", timeSearch.DateTo)})})...func Search(model interface{}, filter interface{}) (result ModelCollection, err error) {    collection := Database.Collection(resolveCollectionName(model))    var cursor *mongo.Cursor    cursor, err = collection.Find(Context, filter)    if err != nil {        log.Fatal(err)    }     for cursor.Next(Context) {        if err := cursor.Decode(model); err != nil {            log.Fatal(err)        }        modelDeref := reflect.ValueOf(model).Elem().Interface()        result = append(result, modelDeref)    }    return}這是我能想到的最接近的游樂場示例。我cursor.Decode()用自己的 Decoding 函數替換了 MongoDB,但這甚至沒有更新父屬性。孩子們還是一樣https://play.golang.org/p/lswJJY0yl80預期的:結果:[{A:1 子級:[{B:11}]} {A:2 子級:[{B:22}]}]實際的:結果:[{A:init 子級:[{B:22}]} {A:init 子級:[{B:22}]}]
查看完整描述

1 回答

?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

您正在解碼為同一個指針,因此您總是會得到一個切片,其中包含的元素的值與您上次解碼的元素的值相同。


相反,您應該在每次迭代中初始化模型類型的新實例,然后解碼為該實例。


result, _ := mongodb.Search(store.Time{}, ...) // pass in non-pointer type to make life easier


// ...


func Search(model interface{}, filter interface{}) (result ModelCollection, err error) {

    collection := Database.Collection(resolveCollectionName(model))


    var cursor *mongo.Cursor

    cursor, err = collection.Find(Context, filter)

    if err != nil {

        log.Fatal(err)

    } 


    for cursor.Next(Context) {

        v := reflect.New(reflect.TypeOf(model)).Interface() // get a new pointer instance

        if err := cursor.Decode(v); err != nil { // decode

            log.Fatal(err)

        }


        md := reflect.ValueOf(v).Elem().Interface()

        result = append(result, md) // append non-pointer value

    }


    return

}


查看完整回答
反對 回復 2023-07-10
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號