Configure Nested
If you want to map
or ignore
a field of a nested type like a map or slice, then you've to define another converter method.
Example, you've want to map
the NestedInput.LastName
to NestedOutput.Surname
for this method.
go
package example
type Input struct {
Name string
Nested NestedInput
}
type Output struct {
Name string
Nested NestedOutput
}
type NestedInput struct{ LastName string }
type NestedOutput struct{ Surname string }
You can't do it like this:
go
// goverter:converter
type Converter interface {
// goverter:map Nested.LastName Nested.Surname
Convert(Input) Output
}
because Goverter dosen't support nested target fields. You have to create another conversion method targeting the nested types like this:
go
package example
// goverter:converter
type Converter interface {
Convert(Input) Output
// goverter:map LastName Surname
ConvertNested(NestedInput) NestedOutput
}
go
// Code generated by github.com/jmattheis/goverter, DO NOT EDIT.
//go:build !goverter
package generated
import nestedstruct "github.com/jmattheis/goverter/example/nested-struct"
type ConverterImpl struct{}
func (c *ConverterImpl) Convert(source nestedstruct.Input) nestedstruct.Output {
var exampleOutput nestedstruct.Output
exampleOutput.Name = source.Name
exampleOutput.Nested = c.ConvertNested(source.Nested)
return exampleOutput
}
func (c *ConverterImpl) ConvertNested(source nestedstruct.NestedInput) nestedstruct.NestedOutput {
var exampleNestedOutput nestedstruct.NestedOutput
exampleNestedOutput.Surname = source.LastName
return exampleNestedOutput
}
go
package example
type Input struct {
Name string
Nested NestedInput
}
type Output struct {
Name string
Nested NestedOutput
}
type NestedInput struct{ LastName string }
type NestedOutput struct{ Surname string }
Slices and Maps
The rule above applies to the conversion of slices and maps too. Field settings must be directly on the struct. This e.g. would be error:
go
// goverter:converter
type Converter interface {
// goverter:map LastName Surname
Convert([]NestedInput) []NestedOutput
}
and should be written as:
go
// goverter:converter
type Converter interface {
Convert([]NestedInput) []NestedOutput
// goverter:map LastName Surname
ConvertNested(NestedInput) NestedOutput
}