使用反射(reflect)动态地合并/合并多个结构体是否可能?

huangapple go评论92阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2015年10月13日 18:59:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/33100910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定