Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
juju812 opened this issue Mar 12, 2021 · 0 comments · Fixed by #93
Closed

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

juju812 opened this issue Mar 12, 2021 · 0 comments · Fixed by #93

Comments

@juju812
Copy link
Contributor

juju812 commented Mar 12, 2021

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}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant