map to anonymous field

This commit is contained in:
2025-09-25 10:00:19 +08:00
parent fd73dd9373
commit de139d0575
2 changed files with 42 additions and 16 deletions

View File

@@ -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 { func copyMap2Struct(dst, src reflect.Value, depth int, _ string, opt *options) error {
// 循环结构然后从map取值 // 循环结构然后从map取值
typ := dst.Type() typ := dst.Type()
for i := 0; i < dst.NumField(); i++ {
for i, n := 0, src.NumField(); i < n; i++ {
field := dst.Field(i) field := dst.Field(i)
sf := typ.Field(i) sf := typ.Field(i)
@@ -184,6 +185,12 @@ func copyMap2Struct(dst, src reflect.Value, depth int, _ string, opt *options) e
continue continue
} }
if sf.Anonymous {
if err := deepCopy(field, src, depth+1, sf.Name, opt); err != nil {
return err
}
}
name := getFieldName(sf) name := getFieldName(sf)
if name == "-" { if name == "-" {
continue continue

View File

@@ -1,6 +1,7 @@
package copier package copier
import ( import (
"encoding/json"
"fmt" "fmt"
"testing" "testing"
"time" "time"
@@ -112,31 +113,49 @@ func TestStructToMapCopy(t *testing.T) {
} }
func TestAnonymousStructToMapCopy(t *testing.T) { func TestAnonymousStructToMapCopy(t *testing.T) {
type person struct { type Person struct {
Name string Name string
Age int Age int
} }
type person2 struct { type person2 struct {
*person *Person
Address *Address Address *Address
} }
src := person2{ // src := person2{
person: &person{ // person: &person{
Name: "John", // Name: "John",
Age: 30, // Age: 30,
}, // },
Address: &Address{ // Address: &Address{
City: "Beijing", // 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 { if err := Copy(&dst, src); err != nil {
t.Fatal(err) t.Fatal(err)
} }
b, _ := json.Marshal(dst)
t.Log(string(b))
})
} }
func TestMapToStructCopy(t *testing.T) { func TestMapToStructCopy(t *testing.T) {