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

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题