douli0531
2015-11-13 09:30
浏览 283
已采纳

golang结构数组转换

I have structs like below:

type Foo struct{
  A string
  B string
}

type Bar struct{
  C string
  D Baz
}

type Baz struct{
  E string
  F string
}

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

A should be C

B should be E

图片转代码服务由CSDN问答提供 功能建议

我有以下结构:

  type Foo struct {  
 A字符串
 B字符串
} 
 
type条形结构{
 C字符串
 D Baz 
} 
 
type Baz结构{
 E字符串
 F字符串
} 
 <  / code>  
 
 

我说我有 [] Bar ,如何将其转换为 [] Foo \ n

A 应该是 C

B 应该是 E < / code>

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyao1994 2015-11-13 09:37
    已采纳

    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.

    func BarsToFoos(bs []Bar) []Foo {
      var acc []Foo
    
      for _, b := range bs {
        newFoo := Foo{A: b.C, B: b.D.E}  // pulled out for clarity
        acc = append(acc, newFoo)
      }
    
      return acc
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongxi1680 2015-11-13 12:12

    For example, concisely mininimizing memory allocations and use,

    package main
    
    import "fmt"
    
    type Foo struct {
        A string
        B string
    }
    
    type Bar struct {
        C string
        D Baz
    }
    
    type Baz struct {
        E string
        F string
    }
    
    func FooFromBar(bs []Bar) []Foo {
        fs := make([]Foo, 0, len(bs))
        for _, b := range bs {
            fs = append(fs, Foo{
                A: b.C,
                B: b.D.E,
            })
        }
        return fs
    }
    
    func main() {
        b := []Bar{{C: "C", D: Baz{E: "E", F: "F"}}}
        fmt.Println(b)
        f := FooFromBar(b)
        fmt.Println(f)
    }
    

    Output:

    [{C {E F}}]
    [{C E}]
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题