在运行时解析传递给函数的结构

Resolve the struct passed to a function in Runtime

我有下面的接口,它为我的持久层实现了一个更简单的类似 Active Record 的实现。

type DBInterface interface {
  FindAll(collection []byte) map[string]string
  FindOne(collection []byte, id int) map[string]string
  Destroy(collection []byte, id int) bool
  Update(collection []byte, obj map[string]string ) map[string]string
  Create(collection []byte, obj map[string]string) map[string]string
}

该应用程序有不同的与之通信的集合和不同的对应模型。我需要能够传入动态 Struct,而不是值 obj 的映射(即更新、创建签名)

我似乎无法理解如何使用反射来解析 Struct ,任何指导都会有所帮助。

有关我正在尝试解释的更多详细信息:

考虑来自 https://labix.org/mgo

的 mgo 示例的以下片段
    err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
               &Person{"Cla", "+55 53 8402 8510"})

当我们向集合中插入数据时,我们做了一个 &Person 我希望能够传入这个位 &Person{"Ale", "+55 53 8116 9639"} 但是接收的方法只会在 运行 时间就知道了。因为它可能是 Person 、 Car 、 Book 等 Struct 取决于调用方法的 func

  1. 将您的对象类型声明为接口{}

         Update(collection []byte, obj interface{} ) map[string]string  
    
  2. 现在您可以将 Person、Book、Car 等作为对象传递给此函数。

  3. 在每个实际结构的更新函数中使用类型开关

        switch t := obj.(type){
        case Car://Handle Car type
        case Perosn:
        case Book:
                      }
    

    需要在编译时决定结构 time.No Go.Even 接口中的动态类型是静态类型。