goverter icon indicating copy to clipboard operation
goverter copied to clipboard

Embedded structs

Open dansimau opened this issue 3 years ago • 1 comments

I have the following scenario:

package example

// goverter:converter
type Converter interface {
	ConvertPerson(source *Person) *APIPerson
}

type Address struct {
	Street string
	City   string
}

type Person struct {
	*Address

	Name string
}

type APIPerson struct {
	Name   string
	Street string
	City   string
}

How can I use goverter to map from a Person to an APIPerson?

I am facing two problems:

  1. Mapping pointer values to non-pointer values
  2. Manually listing all embedded fields

For (1) ideally I would like the target values to either be ignored or set to zero values if the source is nil. For (2) can I somehow map the fields in goverter without having to list them out one by one? I played with mapIdentity but it wasn't clear from the README if this applies to my situation, since it seems like the reverse.

Thanks in advance for your help.

dansimau avatar Jun 07 '22 16:06 dansimau

You could do it like this:

// goverter:converter
// goverter:extend EmptyIfNilString
type Converter interface {
	// goverter:map Address.City City
	// goverter:map Address.Street Street
	ConvertPerson(source *Person) *APIPerson
}

func EmptyIfNilString(s *string) string {
	if s == nil {
		return ""
	}
	return *s
}

The goverter:extend method will be used for every *string to string conversion.

I think goverter could support some kind of auto mapping for nested fields which have the same field names, but this is currently not supported.

jmattheis avatar Jun 07 '22 19:06 jmattheis

Closed in favor of: https://github.com/jmattheis/goverter/issues/55

jmattheis avatar Feb 11 '23 10:02 jmattheis