使用mgo.Marshal()进行指针的封送。

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

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
}

huangapple
  • 本文由 发表于 2015年1月15日 11:00:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/27956149.html
匿名

发表评论

匿名网友

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

确定