Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert one struct to another in Go when one includes another?

Tags:

struct

go

I would like to know if there is easy way to convert from one struct to another in Go when one struct includes the other.

For example

type Type1 struct {
  Field1 int
  Field2 string
}

type Type2 struct {
  Field1 int
}

I know that it can be handled like this

var a Type1{10, "A"}
var b Type2
b.Field1 = a.Field1

but if there are many fields, I will have to write numerous assignments. Is there any other way to handle it without multiple assignments?

In a word, is there anything like b = _.omit(a, 'Field2') in javascript?

like image 548
emil Avatar asked Jan 12 '18 21:01

emil


1 Answers

Not directly, no. You can freely convert between identical types only.

You can get various levels of solutions to this type of problem:

  • writing the assignments out yourself (likely the best performance)
  • using reflection to copy from one to the other based on field names
  • something quick-and-dirty like marshalling one type to JSON then unmarshalling to the other type (which is basically using reflection under the hood with a plaintext middleman, so it's even less efficient, but can be done with little work on your part)
like image 111
Adrian Avatar answered Oct 27 '22 02:10

Adrian