As code shown as below, elements in slices aren't merged but appended due to fromType.ConvertibleTo(toType) is false.
In my view the two struct is identical expect for all fields is ptr type, and if you directly copy the struct it's working fine.
Seems like root cause is behavior of isSlice flag and if from.Kind() == reflect.Slice && to.Kind() == reflect.Slice && fromType.ConvertibleTo(toType) branch isn't consistent. But currently I don't know how to fix this. Could you please provide some clarification and help?
Thx.
type TestStruct struct {
Name string `json:"name"`
Number int `json:"number"`
}
type TestPtrStruct struct {
Name *string `json:"name"`
Number *int `json:"number"`
}
func main() {
s := "def"
ts := []TestStruct{{Name: "abc"}}
tps := []TestPtrStruct{{Name: &s}}
err := copier.Copy(&ts, &tps)
if err != nil {
fmt.Printf("error while copy: %v\n", err)
return
}
fmt.Println(ts)
t := TestStruct{Name: "abc"}
tp := TestPtrStruct{Name: &s}
err = copier.Copy(&t, &tp)
if err != nil {
fmt.Printf("error while copy: %v\n", err)
return
}
fmt.Println(t)
}
As code shown as below, elements in slices aren't merged but appended due to
fromType.ConvertibleTo(toType)
isfalse
. In my view the two struct is identical expect for all fields isptr
type, and if you directly copy the struct it's working fine.Seems like root cause is behavior of
isSlice
flag andif from.Kind() == reflect.Slice && to.Kind() == reflect.Slice && fromType.ConvertibleTo(toType)
branch isn't consistent. But currently I don't know how to fix this. Could you please provide some clarification and help?Thx.
Output:
Expected output: