我希望有某种“钩子(Hook)”,只要我从数据库中获取特定类型的对象,它就会运行。我以为Unmarshaler
接口(interface)非常适合这一点,但是...我如何实现该接口(interface)而不需要自己手动解码每个字段?
我想做这样的事情:
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
}
如何在不使用反射包手动解码字段的情况下实现此目的?
最佳答案
创建另一种类型。它将继承字段,但不会继承方法。因此这里没有无限循环。
func (t *T) UnmarshalBSON(b []byte) error {
type Alias T
bson.Unmarshal(b, (*Alias)(t))
// Do something here
return nil
}
关于go - mongo-go-driver 中的自定义 UnmarshalBSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56400734/