A value implementing the bson.Setter interface will receive the BSON value via the SetBSON method during unmarshaling, and the object itself will not be changed as usual.

If setting the value works, the method should return nil or alternatively bson.SetZero to set the respective field to its zero value (nil for pointer types). If SetBSON returns a value of type bson.TypeError, the BSON value will be omitted from a map or slice being decoded and the unmarshalling will continue. If it returns any other non-nil error, the unmarshalling procedure will stop and error out with the provided value.

This interface is generally useful in pointer receivers, since the method will want to change the receiver. A type field that implements the Setter interface doesn't have to be a pointer, though.

Unlike the usual behavior, unmarshalling onto a value that implements a Setter interface will NOT reset the value to its zero state. This allows the value to decide by itself how to be unmarshalled.

For example:

type MyString string

func (s *MyString) SetBSON(raw bson.Raw) error {
    return raw.Unmarshal(s)

Setter is referenced in 0 repositories