duan_2000 2019-07-24 10:23
浏览 10
已采纳

转到空接口类型声明并创建一个副本

Can't figure out how to modify a struct type variable passed as pointer to a function that takes in an empty interface

I am creating a kind of library that works with MongoDB database through official go driver. I am passing a struct pointer which then gets filled with data from database (MongoDB cursor.Decode). This works fine for a single document, but when I try to return an array of documents, only the parent documents are correct, but children(embedded) stay same for all the elements in array (probably store reference and not the actual value).

Actual code:

// passing model pointer to search function
result, _ := 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
}

Here is the closest playground example I could come up with. I replaced MongoDB cursor.Decode() with my own Decoding function, but this doesn't even update parent properties. Children stay same though

https://play.golang.org/p/lswJJY0yl80

Expected:

result:[{A:1 Children:[{B:11}]} {A:2 Children:[{B:22}]}]

Actual:

result:[{A:init Children:[{B:22}]} {A:init Children:[{B:22}]}]

  • 写回答

1条回答 默认 最新

  • douchun5976 2019-07-24 11:02
    关注

    You're decoding into the same pointer, so you'll always end up with a slice containing elements whose value is the same as the one you decoded last.

    You should instead, on each iteration, initialize a new instance of the model's type and then decode into that.

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?