diff --git a/toolkit/copier/copier.go b/toolkit/copier/copier.go index bfce3299..7e532a47 100644 --- a/toolkit/copier/copier.go +++ b/toolkit/copier/copier.go @@ -78,6 +78,34 @@ func setStructField(structObj any, fieldName string, fieldValue any) error { return nil } + if fieldVal.Kind() == reflect.Ptr { + v := reflect.New(fieldVal.Type().Elem()) + if fieldVal.Type().Elem() != val.Type() { + if val.CanConvert(fieldVal.Type().Elem()) { + v.Elem().Set(val.Convert(fieldVal.Type().Elem())) + fieldVal.Set(v) + return nil + } + } else { + v.Elem().Set(val) + fieldVal.Set(v) + return nil + } + } + + if val.Kind() == reflect.Ptr { + v := val.Elem() + if fieldVal.Type() != v.Type() { + if v.CanConvert(fieldVal.Type()) { + fieldVal.Set(v.Convert(fieldVal.Type())) + return nil + } + } else { + fieldVal.Set(v) + return nil + } + } + if m, ok := fieldValue.(map[string]any); ok { if fieldVal.Kind() == reflect.Struct { @@ -94,7 +122,7 @@ func setStructField(structObj any, fieldName string, fieldValue any) error { } - return fmt.Errorf("map attribute %s value type don't match struct field %s type", fieldName, fName) + return fmt.Errorf("map attribute [%s] value type don't match struct field [%s] type", fieldName, fName) } fieldVal.Set(val) diff --git a/toolkit/copier/copier_test.go b/toolkit/copier/copier_test.go index 5b3a01b8..f55e7631 100644 --- a/toolkit/copier/copier_test.go +++ b/toolkit/copier/copier_test.go @@ -2,7 +2,7 @@ package copier import ( "fmt" - "github.com/bytedance/sonic/decoder" + "github.com/samber/lo" "testing" ) @@ -169,13 +169,15 @@ func TestDeepCopy2(t *testing.T) { } func TestDeepCopy3(t *testing.T) { - t1 := `{"name":"jack", "age": 18.0, "school": "beijing"}` + //t1 := `{"name":"jack", "age": 18.0, "school": "beijing"}` p := make(map[string]interface{}) - dec := decoder.NewDecoder(t1) - dec.UseInt64() - dec.Decode(&p) - ddd, _ := json.Marshal(p) - fmt.Println(string(ddd)) + p["name"] = lo.ToPtr("jack") + p["age"] = lo.ToPtr(18) + //dec := decoder.NewDecoder(t1) + //dec.UseInt64() + //dec.Decode(&p) + //ddd, _ := json.Marshal(p) + //fmt.Println(string(ddd)) type Student struct { Name string `json:"name"` Age int `json:"age,string"`