1 回答
TA贡献1797条经验 获得超4个赞
我实现了MarshalerandUnmarshaler接口。由于 mongo 驱动程序调用MarshalBSON并且UnmarshalBSON如果类型实现Marshaler并且Unmarshaler我们也最终陷入无限循环。为了避免这种情况,我们创建了type. 别名Golang仅继承字段而不是方法,因此我们最终调用正常bson.Marshal和bson.Unmarshal
func (r *ReallyBig) MarshalBSON() ([]byte, error) {
type ReallyBigAlias ReallyBig
reallyBigRaw, err := getRaw(r.ReallyBigObj)
if err != nil {
return nil, err
}
r.ReallyBigRaw = reallyBigRaw
return bson.Marshal((*ReallyBigAlias)(r))
}
func (r *ReallyBig) UnmarshalBSON(data []byte) error {
type ReallyBigAlias ReallyBig
err := bson.Unmarshal(data, (*ReallyBigAlias)(r))
if err != nil {
return err
}
reallyBigProto, err := getProto(r.ReallyBigRaw)
if err != nil {
return err
}
r.ReallyBigObj = reallyBigProto
return nil
}
- 1 回答
- 0 关注
- 148 浏览
添加回答
举报