Search code examples
gomgo

Marshalling pointers using mgo.Marshal()


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?


Solution

  • 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
    }