copier icon indicating copy to clipboard operation
copier copied to clipboard

copy of slice doesn't replace the whole slice

Open watercraft opened this issue 1 year ago • 3 comments

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 6ffbdf1ce61d595f10c98c3177cc821218379e7e

watercraft avatar Apr 30 '23 23:04 watercraft

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)
}

watercraft avatar May 04 '23 19:05 watercraft

Same problem.

jheroy avatar May 17 '23 07:05 jheroy

遇到同样的问题

amosnothing avatar Oct 20 '23 10:10 amosnothing