go - Why can not I copy a slice with copy in golang? -


i need make copy of slice in go , reading docs there copy function @ disposal.

the copy built-in function copies elements source slice destination slice. (as special case, copy bytes string slice of bytes.) source , destination may overlap. copy returns number of elements copied, minimum of len(src) , len(dst).

but when do

arr := []int{1, 2, 3} tmp := []int{} copy(tmp, arr) fmt.println(tmp) fmt.println(arr) 

my tmp empty before (i tried use arr, tmp):

[] [1 2 3] 

you can check on go playground. why can not copy slice?

the builtin copy(dst, src) copies min(len(dst), len(src)) elements.

so if dst empty (len(dst) == 0), nothing copied.

try tmp := make([]int, len(arr)) (go playground):

arr := []int{1, 2, 3} tmp := make([]int, len(arr)) copy(tmp, arr) fmt.println(tmp) fmt.println(arr) 

output (as expected):

[1 2 3] [1 2 3] 

unfortunately not documented in builtin package, documented in go language specification: appending , copying slices:

the number of elements copied minimum of len(src) , len(dst).

edit:

finally documentation of copy() has been updated , contains fact minimum length of source , destination copied:

copy returns number of elements copied, minimum of len(src) , len(dst).


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -