Golang结构体数组转换

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

golang struct array conversion

问题

我有以下结构体:

  1. type Foo struct{
  2. A string
  3. B string
  4. }
  5. type Bar struct{
  6. C string
  7. D Baz
  8. }
  9. type Baz struct{
  10. E string
  11. F string
  12. }

假设我有一个 []Bar,如何将其转换为 []Foo

A 应该是 C

B 应该是 E

英文:

I have structs like below:

  1. type Foo struct{
  2. A string
  3. B string
  4. }
  5. type Bar struct{
  6. C string
  7. D Baz
  8. }
  9. type Baz struct{
  10. E string
  11. F string
  12. }

Lets say I have []Bar, how to convert this to []Foo ?

A should be C

B should be E

答案1

得分: 5

我不认为有任何“神奇”的方法可以进行转换。然而,创建它只需要很少的代码。像这样的代码应该可以解决问题。

  1. func BarsToFoos(bs []Bar) []Foo {
  2. var acc []Foo
  3. for _, b := range bs {
  4. newFoo := Foo{A: b.C, B: b.D.E} // 为了清晰起见而提取出来
  5. acc = append(acc, newFoo)
  6. }
  7. return acc
  8. }

这段代码将一个类型为[]Bar的切片转换为一个类型为[]Foo的切片。在循环中,它遍历每个Bar对象,并使用其中的字段值创建一个新的Foo对象,然后将其添加到acc切片中。最后,返回acc切片作为结果。

英文:

I don't think there's any "magic" way of doing the conversion. However, it is a very small piece of coding to create it. Something like this ought to do the trick.

  1. func BarsToFoos(bs []Bar) []Foo {
  2. var acc []Foo
  3. for _, b := range bs {
  4. newFoo := Foo{A: b.C, B: b.D.E} // pulled out for clarity
  5. acc = append(acc, newFoo)
  6. }
  7. return acc
  8. }

答案2

得分: 2

例如,简洁地最小化内存分配和使用,

  1. package main
  2. import "fmt"
  3. type Foo struct {
  4. A string
  5. B string
  6. }
  7. type Bar struct {
  8. C string
  9. D Baz
  10. }
  11. type Baz struct {
  12. E string
  13. F string
  14. }
  15. func FooFromBar(bs []Bar) []Foo {
  16. fs := make([]Foo, 0, len(bs))
  17. for _, b := range bs {
  18. fs = append(fs, Foo{
  19. A: b.C,
  20. B: b.D.E,
  21. })
  22. }
  23. return fs
  24. }
  25. func main() {
  26. b := []Bar{{C: "C", D: Baz{E: "E", F: "F"}}}
  27. fmt.Println(b)
  28. f := FooFromBar(b)
  29. fmt.Println(f)
  30. }

输出:

  1. [{C {E F}}]
  2. [{C E}]
英文:

For example, concisely mininimizing memory allocations and use,

  1. package main
  2. import "fmt"
  3. type Foo struct {
  4. A string
  5. B string
  6. }
  7. type Bar struct {
  8. C string
  9. D Baz
  10. }
  11. type Baz struct {
  12. E string
  13. F string
  14. }
  15. func FooFromBar(bs []Bar) []Foo {
  16. fs := make([]Foo, 0, len(bs))
  17. for _, b := range bs {
  18. fs = append(fs, Foo{
  19. A: b.C,
  20. B: b.D.E,
  21. })
  22. }
  23. return fs
  24. }
  25. func main() {
  26. b := []Bar{{C: "C", D: Baz{E: "E", F: "F"}}}
  27. fmt.Println(b)
  28. f := FooFromBar(b)
  29. fmt.Println(f)
  30. }

Output:

  1. [{C {E F}}]
  2. [{C E}]

huangapple
  • 本文由 发表于 2015年11月13日 17:30:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/33689553.html
匿名

发表评论

匿名网友

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

确定