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

copy of slice doesn't replace the whole slice #182

Closed
watercraft opened this issue Apr 30, 2023 · 3 comments
Closed

copy of slice doesn't replace the whole slice #182

watercraft opened this issue Apr 30, 2023 · 3 comments
Assignees

Comments

@watercraft
Copy link

Reproducible Example

package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

func main() {
	dst := []byte("(to be replaced)(extra stuff)")
	src := []byte("(replacement --)")
	copier.Copy(&dst, &src)
	fmt.Printf("Result: %s\n", string(dst))
	//   Result: (replacement --)(extra stuff)
	// Expected: (replacement --)
}

Description

If this is expected behavior I would appreciate an option to override the entire destination slice. DeepCopy doesn't do it.
The issue appears to be introduced in 6ffbdf1

@watercraft
Copy link
Author

Created this wrapper module to work around this issue:

package copier

import (
	"reflect"

	"github.com/jinzhu/copier"
)

func Copy(dst, src interface{}) {
	dv := reflect.ValueOf(dst)
	tv := reflect.TypeOf(dst)
	if dv.Kind() == reflect.Ptr {
		dv = reflect.Indirect(dv)
		tv = reflect.TypeOf(dv.Interface())
	}
	sv := reflect.ValueOf(src)
	if sv.Kind() == reflect.Ptr {
		sv = reflect.Indirect(sv)
	}
	if dv.Kind() == reflect.Slice {
		dv.Set(reflect.MakeSlice(reflect.SliceOf(tv.Elem()), sv.Len(), sv.Len()))
	}
	copier.Copy(dst, src)
}

@jheroy
Copy link
Contributor

jheroy commented May 17, 2023

Same problem.

jheroy added a commit to jheroy/copier that referenced this issue May 17, 2023
@System-Glitch System-Glitch mentioned this issue Oct 16, 2023
2 tasks
@amosnothing
Copy link

遇到同样的问题

@jinzhu jinzhu closed this as completed in 7e37c0f Mar 17, 2024
jinzhu added a commit that referenced this issue Mar 17, 2024
fix #182 copy of slice doesn't replace the whole slice
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

No branches or pull requests

4 participants