How to convert a struct to a different struct with fewer fields

There is no built-in support for this. If you really need this, you could write a general function which uses reflection to copy the fields.

Or you could redesign. If Big is a Small plus some other, additional fields, why not reuse Small in Big?

type Small struct {
    A int
    B string
}

type Big struct {
    S Small
    C float
    D byte
}

Then if you have a Big struct, you also have a Small: Big.S. If you have a Small and you need a Big: Big{S: small}.

If you worry about losing the convenience of shorter field names, or different marshalled results, then use embedding instead of a named field:

type Big struct {
    Small // Embedding
    C float
    D byte
}

Then these are also valid: Big.A, Big.B. But if you need a Small value, you can refer to the embedded field using the unqualified type name as the field name, e.g. Big.Small (see Golang embedded struct type). Similarly, to create a Big from a Small: Big{Small: small}.


Is there a way of converting between Big to Small (and maybe even vice-versa) without using a Convert function?

The only option is to do it manually, as you have done. Whether you wrap that in a function or not, is a matter of taste/circumstance.

Tags:

Struct

Go