gpt4 book ai didi

go - mongo-go-driver 中的自定义 UnmarshalBSON

转载 作者:行者123 更新时间:2023-12-03 03:20:48 25 4
gpt4 key购买 nike

我希望有某种“钩子(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com