GoMapper is a library for struct to struct mapping.
There are two use cases: Manual and Auto.
Manual
mode allows you to specify a function to convert one structure to another.Auto
mode uses matching field names for automatic conversion; it is important that not only the field names match, but also their types. This mode also supports structures in structure fields and automatically works by matching field names. It's based onfmapswitch case and reflect based library.
Both modes are route based. In which the reflect.Type of the source structure and the type of the destination structure are specified. If such a route was not found, gomapper will return an error.
Alsogomapper
support slices, you don't need to specify types of slices for mapping.
go get github /insei/gomapper@latest
You can found a lot of examples in tests.
Manual route.
packagemain
import(
"fmt"
"github /insei/gomapper"
)
typeSourcestruct{
Namestring
Ageuint8
}
typeDeststruct{
NameCustomstring
Ageuint8
}
funcmain() {
err:=gomapper.AddRoute[Source,Dest](func(sourceSource,dest*Dest)error{
dest.NameCustom=source.Name
dest.Age=source.Age
returnnil
})
iferr!=nil{
panic(err)
}
s:=Source{
Name:"DefaultName",
Age:16,
}
dest,err:=gomapper.MapTo[Dest](s)
// or gomapper.MapTo[Dest](&s)
// or d:= Dest{}
// gomapper.Map(&s, &d)
iferr!=nil{
panic(err)
}
fmt.Print(dest)
}
Auto Route.
packagemain
import(
"fmt"
"github /insei/gomapper"
)
typeSourcestruct{
Namestring
Ageuint8
}
typeDeststruct{
NameCustomstring
Ageuint8
}
funcmain() {
err:=gomapper.AutoRoute[Source,Dest]()
iferr!=nil{
panic(err)
}
s:=Source{
Name:"DefaultName",
Age:16,
}
dest,err:=gomapper.MapTo[Dest](s)
// or gomapper.MapTo[Dest](&s)
// or dest:= Dest{}
// gomapper.Map(&s, &dest)
iferr!=nil{
panic(err)
}
fmt.Print(dest)
}
Map structs into slices.
packagemain
import(
"fmt"
"github /insei/gomapper"
)
typeSourcestruct{
Namestring
Ageuint8
}
typeDeststruct{
NameCustomstring
Ageuint8
}
funcmain() {
err:=gomapper.AutoRoute[Source,Dest]()// or manual
iferr!=nil{
panic(err)
}
s:=Source{
Name:"DefaultName",
Age:16,
}
sSlice:=[]Source{s}
sDest,err:=gomapper.MapTo[[]Dest](sSlice)
// or sDest:= []Dest{}
// sDest, err:= gomapper.MapTo(sSlice, &sDest)
iferr!=nil{
panic(err)
}
fmt.Print(sDest)
}