map to anonymous field
This commit is contained in:
@@ -176,7 +176,8 @@ func copyStruct2Map(dst, src reflect.Value, depth int, fieldName string, opt *op
|
||||
func copyMap2Struct(dst, src reflect.Value, depth int, _ string, opt *options) error {
|
||||
// 循环结构,然后从map取值
|
||||
typ := dst.Type()
|
||||
for i := 0; i < dst.NumField(); i++ {
|
||||
|
||||
for i, n := 0, src.NumField(); i < n; i++ {
|
||||
field := dst.Field(i)
|
||||
sf := typ.Field(i)
|
||||
|
||||
@@ -184,6 +185,12 @@ func copyMap2Struct(dst, src reflect.Value, depth int, _ string, opt *options) e
|
||||
continue
|
||||
}
|
||||
|
||||
if sf.Anonymous {
|
||||
if err := deepCopy(field, src, depth+1, sf.Name, opt); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
name := getFieldName(sf)
|
||||
if name == "-" {
|
||||
continue
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package copier
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -112,31 +113,49 @@ func TestStructToMapCopy(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAnonymousStructToMapCopy(t *testing.T) {
|
||||
type person struct {
|
||||
type Person struct {
|
||||
Name string
|
||||
Age int
|
||||
}
|
||||
|
||||
type person2 struct {
|
||||
*person
|
||||
*Person
|
||||
Address *Address
|
||||
}
|
||||
|
||||
src := person2{
|
||||
person: &person{
|
||||
Name: "John",
|
||||
Age: 30,
|
||||
},
|
||||
Address: &Address{
|
||||
City: "Beijing",
|
||||
// src := person2{
|
||||
// person: &person{
|
||||
// Name: "John",
|
||||
// Age: 30,
|
||||
// },
|
||||
// Address: &Address{
|
||||
// City: "Beijing",
|
||||
// },
|
||||
// }
|
||||
|
||||
// dst := map[string]any{}
|
||||
// if err := Copy(&dst, src); err != nil {
|
||||
// t.Fatal(err)
|
||||
// }
|
||||
|
||||
t.Run("test to anonymous struct", func(t *testing.T) {
|
||||
src := map[string]any{
|
||||
"Name": "John",
|
||||
"Age": 30,
|
||||
"Address": map[string]any{
|
||||
"City": "Beijing",
|
||||
},
|
||||
}
|
||||
|
||||
dst := map[string]any{}
|
||||
dst := person2{}
|
||||
if err := Copy(&dst, src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
b, _ := json.Marshal(dst)
|
||||
t.Log(string(b))
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func TestMapToStructCopy(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user