为了账号安全,请及时绑定邮箱和手机立即绑定

清空接口类型断言并创建副本

清空接口类型断言并创建副本

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 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信