写了个go结构体映射工具
go
package main
import (
"github.com/yowayimono/mapper/mapper"
"reflect"
"testing"
)
type SourceStruct struct {
Username string
Password string
Phone string
}
type TargetStruct struct {
Username string
Password string
Phone string
}
type NestedStruct struct {
Field1 string
Field2 int
}
type SourceStructWithNested struct {
Username string
Password string
Phone string
Nested NestedStruct
}
type TargetStructWithNested struct {
Username string
Password string
Nested NestedStruct
}
func TestMapFields(t *testing.T) {
source := SourceStructWithNested{
Username: "john",
Password: "password123",
Phone: "1234567890",
Nested: NestedStruct{
Field1: "1234",
Field2: 18,
},
}
target := TargetStructWithNested{}
mapper.Maps(&source, &target)
expected := TargetStructWithNested{
Username: "john",
Password: "password123",
Nested: NestedStruct{
Field1: "1234",
Field2: 18,
},
}
if !reflect.DeepEqual(target, expected) {
t.Errorf("MapFields did not map the fields correctly. Expected: %v, got: %v", expected, target)
}
}
支持嵌套映射结构体,支持标签
gopackage main
import (
"github.com/yowayimono/mapper/mapper"
"reflect"
"testing"
)
type Source struct {
ID int
Name string
}
type Target struct {
IDY int `mapper:"ID"`
}
func TestMap(t *testing.T) {
source := &Source{
ID: 1,
Name: "John Doe",
}
target := &Target{}
mapper.Map(source, target)
expected := Target{
IDY: 1,
}
if !reflect.DeepEqual(*target, expected) {
t.Errorf("Mapping failed. Expected %+v, got %+v", expected, *target)
}
}
标签映射还不支持嵌套
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!