2

我希望有某种“钩子”,只要我从数据库中获取特定类型的对象,它就会运行。我认为该Unmarshaler接口非常适合,但是...如何在不自己手动解组每个字段的情况下实现该接口?

我想过做这样的事情:

func (t *T) UnmarshalBSON(b []byte) error {
    // Simply unmarshal `b` into `t` like it would otherwise
    bson.Unmarshal(b, t) // Obviously this won't work, it'll be an infinite loop
    // Do something here
    return nil
}

如果不使用反射 pkg 手动解组字段,我怎么能做到这一点?

4

1 回答 1

4

制作另一种类型。它将继承字段,但不继承方法。因此这里没有无限循环。

func (t *T) UnmarshalBSON(b []byte) error {
    type Alias T
    bson.Unmarshal(b, (*Alias)(t))
    // Do something here
    return nil
}
于 2019-10-17T08:30:53.973 回答