0

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?

Bernard
  • 16,149
  • 12
  • 63
  • 66

1 Answers1

2

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
}
OneOfOne
  • 95,033
  • 20
  • 184
  • 185
  • Yes, that's a workaround although that causes trouble elsewhere; Item and AssociatedItem are not the same type anymore so you give up being able to put them both into the same array, pass them to functions as Tool or assigning them to a Tool variable. – Bernard Jan 19 '15 at 03:37
  • @Alkaline there isn't really any other way, i guess you can add an exported bool field to tool and set it to true and setbson can check it. – OneOfOne Jan 19 '15 at 10:00