duanmanmian7589 2013-05-05 19:19
浏览 57
已采纳

防止mgo / bson Unmarshal清除未导出的字段

I try to populate the exported fields of a struct with content fetched from a MongoDb-database using the labix.org/v2/mgo package.

mgo uses the labix.org/v2/mgo/bson package to unmarshal the data. But the unmarshaller sets all unexported fields to their zero value.

Is there any way to prevent this behavior?

Working example:

package main

import (
    "fmt"
    "labix.org/v2/mgo/bson"
)

type Sub struct{ Int int }

type Player struct {
    Name       string
    unexpInt   int
    unexpPoint *Sub
}

func main() {
    dta,err := bson.Marshal(bson.M{"name": "ANisus"})
    if err != nil {
        panic(err)
    }

    p := &Player{unexpInt: 12, unexpPoint: &Sub{42}}

    fmt.Printf("Before: %+v
", p)
    err = bson.Unmarshal(dta, p)
    if err != nil {
        panic(err)
    }
    fmt.Printf("After: %+v
", p)
}

Output:

Before: &{Name: unexpInt:12 unexpPoint:0xf84005f500}
After: &{Name:ANisus unexpInt:0 unexpPoint:<nil>}
  • 写回答

1条回答 默认 最新

  • douweng3383 2013-05-08 00:16
    关注

    This is not possible. As you can see in the source code, struct values are explicitly being set to their zero value before filling in any fields.

    There is no option to disable this behaviour. It is presumably in place to make sure the result of Unmarshal() only depends on the BSON data and not any prior state.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件