0

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

2
  • Those structs are semantically different. Please describe why you want to do that conversion, maybe you can use an interface. Commented Nov 13, 2015 at 9:35
  • I'm using third party package for something, this package returns me a huge struct, I want to convert this struct to my local struct for insert to db. Commented Nov 13, 2015 at 9:38

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

9 Comments

@MelihMucuk yes, it should be enough. Over optimization is the root of all evil.
I doubt there's a faster way to actually convert them. Depending on exactly what you're trying to do, it MAY be better to use an interface and skipping the explicit conversion.
I think it's better to define length and capacity of acc slice, to reduce memory allocations. Because we know that: len(bs)
That's sufficiently "micro" in optimization terms that I thought it would make the example less readable. But, sure, that's going to give you a slight run-time performace. I'd still bench-mark both versions with, say, 10, 100 and 1000 elements and see if it's actually worth it...
I'm not really sure that acc := make([]Foo, 0, len(bs)) is less readable
|
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.