英文:
Is it possible to merge/merge multiple structs into one dynamically (using reflect)?
问题
我需要构建一个函数,将多个其他函数的响应合并为一个(结构体)。目前我在考虑的唯一方法是创建一个map[string]interface{},然后遍历我需要合并的结构体的字段,并将字段名->值作为键,值存储在map中。还有其他方法吗?我基本上只需要将两个结构体嵌入到一个结构体中。
英文:
I need to build a function which merges responses from multiple other functions into one (struct). Currently I'm thinking that the only way would be to create a map[string]interface{} and then range over the fields of structs I need to merge and assign field name -> value as key, values in the map. Is there any other way? I basically just need to embed two structs into one.
答案1
得分: 1
我不确定这是否回答了你的问题,但你绝对可以将结构体嵌入到另一个结构体中,并直接访问属性。你不需要使用反射,而且我要补充一点,反射经常被人们所不赞同,因为更推荐显式编码;反射通常是隐式的。
以下是一些代码,希望能解决你的问题:
type Foo struct {
Bar
Baz
}
type Bar struct {
BarValue string
}
type Baz struct {
BazValue string
}
func main() {
test := Foo{Bar: Bar{BarValue: "bar"}, Baz: Baz{BazValue: "baz"}}
fmt.Println(test.BarValue)
fmt.Println(test.BazValue)
}
英文:
I'm not sure if this answers your question but you can definitely embed structs into one struct and access the properties directly. You wouldn't need to use reflection and might I add that its often the case that reflection is frowned upon since its more preferable to be explicit; reflection is often implicit.
Here is some code, that hopefully addresses what you wanted:
type Foo struct {
Bar
Baz
}
type Bar struct {
BarValue string
}
type Baz struct {
BazValue string
}
func main() {
test := Foo{Bar: Bar{BarValue: "bar"}, Baz: Baz{BazValue: "baz"}}
fmt.Println(test.BarValue)
fmt.Println(test.BazValue)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论