Skip to content

Setting: autoMap

autoMap PATH can be defined as method comment.

You can use autoMap to automatically match fields from a sub struct to the target struct. This is useful, when you've a struct that is the flattened version of another struct.

autoMap PATH accepts one parameter which is a path to a substruct on the source struct. You can specify nested substructs by separating the fields with .. Example: Nested.SubStruct

If there are ambiguities, then goverter will fail with an error.

go
package example

// goverter:converter
type Converter interface {
	// goverter:autoMap Address
	Convert(Person) FlatPerson
}

type Person struct {
	Name    string
	Age     int
	Address Address
}
type Address struct {
	Street  string
	ZipCode string
}
type FlatPerson struct {
	Name    string
	Age     int
	Street  string
	ZipCode string
}
go
// Code generated by github.com/jmattheis/goverter, DO NOT EDIT.
//go:build !goverter

package generated

import automap "github.com/jmattheis/goverter/example/auto-map"

type ConverterImpl struct{}

func (c *ConverterImpl) Convert(source automap.Person) automap.FlatPerson {
	var exampleFlatPerson automap.FlatPerson
	exampleFlatPerson.Name = source.Name
	exampleFlatPerson.Age = source.Age
	exampleFlatPerson.Street = source.Address.Street
	exampleFlatPerson.ZipCode = source.Address.ZipCode
	return exampleFlatPerson
}