英文:
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
}
应用程序与不同的集合进行通信,并有不同的对应模型。我希望能够传递一个动态的结构体,而不是一个map作为值obj(即Update,Create的参数)。
我似乎无法理解如何使用反射来解析结构体,希望能得到一些指导。
我试图解释一下我所尝试的内容:
考虑以下来自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等结构体,具体取决于调用该方法的函数。
英文:
I have the below interface that implements a simpler Active Record Like implementation for my persistent layer.
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
}
The application has different collection's that it talks to and different corresponding models. I need to be able to pass in a dynamic Struct , instead of a map for the value obj ( ie. Update , Create Signatures )
I can't seem to understand how to use reflection to resolve the Struct , any guidance would help.
More details on what I am trying explain :
Consider the below snippet from mgo example from https://labix.org/mgo
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
&Person{"Cla", "+55 53 8402 8510"})
When we insert data to the collection , we do a &Person I want to be able to pass in this bit &Person{"Ale", "+55 53 8116 9639"} but the method receiving the would only know it in the Run time. Because it could be a Person , Car , Book etc Struct depending on the func calling the method
答案1
得分: 1
-
将你的对象类型声明为 interface{}
Update(collection []byte, obj interface{}) map[string]string
-
现在你可以将 Person、Book、Car 等作为 obj 传递给这个函数。
-
在 Update 函数内部使用类型切换来处理每个实际的结构体
switch t := obj.(type){ case Car://处理 Car 类型 case Person: case Book: }
在 Go 中,结构体需要在编译时确定。Go 中没有动态类型,甚至接口也是静态类型的。
英文:
-
Declare your obj type as interface{}
Update(collection []byte, obj interface{} ) map[string]string
-
Now you can pass Person,Book,Car etc to this function as obj.
-
Use a type switch inside Update function for each actual struct
switch t := obj.(type){ case Car://Handle Car type case Perosn: case Book: }
Structs needs to be decided at compile time.No dynamic types in Go.Even interfaces are static types.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论