goverter
goverter copied to clipboard
Embedded structs
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:
- Mapping pointer values to non-pointer values
- 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.
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.
Closed in favor of: https://github.com/jmattheis/goverter/issues/55