jinzhu / copier

Copier for golang, copy value from struct to struct and more
MIT License
5.58k stars 489 forks source link

Elements in slices can't be merged due to not convertible #92

Closed juju812 closed 3 years ago

juju812 commented 3 years ago

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)

}

Output:

[{abc 0} {def 0}]
{def 0}

Expected output:

[{def 0}]
{def 0}