Update an existing instance
When you already have an existing instance to a struct and want to update a couple of fields from a different type, then you can use update ARG
to instruct goverter to create a conversion that updates an instance passed as argument.
go
package update
// goverter:converter
type Converter interface {
// goverter:update target
Convert(source Input, target *Output)
}
type Input struct {
Name *string
Aliases []string
Age int
}
type Output struct {
Name *string
Aliases []string
Age int
}
go
// Code generated by github.com/jmattheis/goverter, DO NOT EDIT.
//go:build !goverter
package generated
import update "github.com/jmattheis/goverter/example/update"
type ConverterImpl struct{}
func (c *ConverterImpl) Convert(source update.Input, target *update.Output) {
if source.Name != nil {
xstring := *source.Name
target.Name = &xstring
}
if source.Aliases != nil {
target.Aliases = make([]string, len(source.Aliases))
for i := 0; i < len(source.Aliases); i++ {
target.Aliases[i] = source.Aliases[i]
}
}
target.Age = source.Age
}
Don't override zero values
If you have fields that aren't pointers, then you may want to enable update:ignoreZeroValueField
to skip overriding those with the unset values.
go
package update
// goverter:converter
// goverter:update:ignoreZeroValueField
// ^- this setting can be specified on the conversion method
type WithIgnore interface {
// goverter:update target
Convert(source Input, target *Output)
}
// goverter:converter
type WithoutIgnore interface {
// goverter:update target
Convert(source Input, target *Output)
}
type Input struct {
Name string
Age int
Cool bool
Address *string
}
type Output struct {
Name string
Age int
Cool bool
Address *string
}
go
// Code generated by github.com/jmattheis/goverter, DO NOT EDIT.
//go:build !goverter
package generated
import updateignorezero "github.com/jmattheis/goverter/example/update-ignore-zero"
type WithIgnoreImpl struct{}
func (c *WithIgnoreImpl) Convert(source updateignorezero.Input, target *updateignorezero.Output) {
if source.Name != "" {
target.Name = source.Name
}
if source.Age != 0 {
target.Age = source.Age
}
if source.Cool != false {
target.Cool = source.Cool
}
if source.Address != nil {
xstring := *source.Address
target.Address = &xstring
}
}
type WithoutIgnoreImpl struct{}
func (c *WithoutIgnoreImpl) Convert(source updateignorezero.Input, target *updateignorezero.Output) {
target.Name = source.Name
target.Age = source.Age
target.Cool = source.Cool
if source.Address != nil {
xstring := *source.Address
target.Address = &xstring
}
}