Melih Mucuk
Melih Mucuk

Reputation: 7066

golang struct array conversion

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

Upvotes: 0

Views: 7206

Answers (2)

peterSO
peterSO

Reputation: 166529

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

Upvotes: 2

Vatine
Vatine

Reputation: 21238

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
}

Upvotes: 5

Related Questions