0

So I have a question that I've been trying to figure out for a while and hopefully someone has some insight. Basically, I have two similar, but different structs in Go and I would like to convert between them.

Something like the following:

type A struct {
    Name string
}

type B struct {
    Name NameStruct
}

type NameStruct struct {
    Firstname string
    Lastname string
}

In this example,

B.Name == NameStruct{
              Firstname: strings.Split(A.Name, " ")[0],
              Lastname:  strings.Split(A.Name, " ")[1],
          }

Basically I would like to be able to define a mapping of fields from one struct to the other as well as a conversion function, so that I can do this without writing all of the code to do the conversion manually.

What I'm imagining is that there might be some sort of Go generator out there that could do something like this. I don't think it is possible using reflection because of the nested structs (although I'm open to suggestions).

Basically, does anyone know of a way to do this that is better than either writing conversion code manually or creating my own generator?

Sam G-H
  • 627
  • 6
  • 17
  • I don't think there is anything wrong with a function taking an `A` as an argument and returning a `B` – Dean Elbaz Aug 26 '16 at 15:53
  • Thing is I don't want to do that because, while this example is very short and sweet, my actual structs are quite large and have multiple different types nested and nested within those. It just gets to be a ton of code – Sam G-H Aug 26 '16 at 16:04
  • 2
    Would it be possible for you to not convert them and use interfaces instead? (without seeing some code, I can't really be helpful here) – Dean Elbaz Aug 26 '16 at 16:13
  • 1
    You may be on to something with using interfaces – Sam G-H Aug 26 '16 at 16:37

0 Answers0