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

huangapple go评论67阅读模式
英文:

Prevent mgo/bson Unmarshal to clear unexported fields

问题

我试图使用从MongoDb数据库中获取的内容填充一个结构体的导出字段,使用的是labix.org/v2/mgo包。

mgo使用labix.org/v2/mgo/bson包来解组数据。但是解组器会将所有未导出的字段设置为它们的零值。

有没有办法阻止这种行为?

工作示例:

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\n", p)
	err = bson.Unmarshal(dta, p)
	if err != nil {
		panic(err)
	}
	fmt.Printf("After: %+v\n", p)
}

输出:

Before: &{Name: unexpInt:12 unexpPoint:0xf84005f500}
After: &{Name:ANisus unexpInt:0 unexpPoint:<nil>>
英文:

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 (
	&quot;fmt&quot;
	&quot;labix.org/v2/mgo/bson&quot;
)

type Sub struct{ Int int }

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

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

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

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

Output:

Before: &amp;{Name: unexpInt:12 unexpPoint:0xf84005f500}
After: &amp;{Name:ANisus unexpInt:0 unexpPoint:&lt;nil&gt;}

答案1

得分: 2

这是不可能的。正如您可以在源代码中看到的那样,struct 值在填充任何字段之前都被明确地设置为它们的零值。

没有选项可以禁用这种行为。这可能是为了确保 Unmarshal() 的结果仅取决于 BSON 数据,而不是任何先前的状态。

英文:

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.

huangapple
  • 本文由 发表于 2013年5月6日 03:19:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/16388210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定