英文:
Marshalling pointers using mgo.Marshal()
问题
我想要对指针和数值进行不同的编码。目前,如果我们有一个结构体:
type Order struct {
Item Tool
AssociatedItem *Tool
}
在编组时,它们都会被内联到一个名为Order的文档中。
在处理*Tool的情况下,我需要能够执行自己的序列化操作。例如,在这种情况下,我只想存储Tool的Id而不是整个内容。不幸的是,mgo中的覆盖机制是为Tool定义SetBSON()和GetBSON(),但它不能区分指针和非指针。
处理这个问题的最佳方法是什么?
英文:
I want to encode pointers differently than from values. Currently, if we have a struct:
type Order struct {
Item Tool
AssociatedItem *Tool
}
both get inlined into a Order document inside mongo when marshalling.
I need to be able to perform my own serialization in the case of a *Tool. For instance, I could in this case only store the Id for the Too instead of the whole content. Unfortunately the overriding mechanism in mgo is to define a SetBSON() GetBSON for the Tool but it doesn't differentiate between pointers and non pointers.
What would be the best way to handle this?
答案1
得分: 2
使用不同类型的“指针”,例如:
type SelectiveTool Tool
func (st *SelectiveTool) SetBSON(raw bson.Raw) error {
return raw.Unmarshal(s)
}
type Order struct {
Item Tool
AssociatedItem *SelectiveTool
}
英文:
Use a different type for "pointers", for example:
type SelectiveTool Tool
func (st *SelectiveTool) SetBSON(raw bson.Raw) error {
return raw.Unmarshal(s)
}
type Order struct {
Item Tool
AssociatedItem *SelectiveTool
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论