Skip to content

Commit

Permalink
copier DeepCopy
Browse files Browse the repository at this point in the history
  • Loading branch information
wubin48435 committed Aug 21, 2024
1 parent 62f4f81 commit d4ab04d
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 8 deletions.
30 changes: 29 additions & 1 deletion toolkit/copier/copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
16 changes: 9 additions & 7 deletions toolkit/copier/copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package copier

import (
"fmt"
"github.com/bytedance/sonic/decoder"
"github.com/samber/lo"
"testing"
)

Expand Down Expand Up @@ -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"`
Expand Down

0 comments on commit d4ab04d

Please sign in to comment.