【问题标题】:Custom UnmarshalBSON in mongo-go-drivermongo-go-driver 中的自定义 UnmarshalBSON
【发布时间】:2019-10-17 10:29:11
【问题描述】:

我想要某种“挂钩”,只要我从数据库中获取特定类型的对象,它就会运行。我认为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 手动解组字段的情况下实现此目的?

【问题讨论】:

标签: go mongo-go


【解决方案1】:

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

func (t *T) UnmarshalBSON(b []byte) error {
    type Alias T
    bson.Unmarshal(b, (*Alias)(t))
    // Do something here
    return nil
}

【讨论】:

  • 完美答案。
猜你喜欢
  • 1970-01-01
  • 2019-07-13
  • 2019-05-21
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 2018-09-30
相关资源
最近更新 更多