Saturday, September 9, 2017

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

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

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

Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

So if your dst is empty (len(dst) == 0), nothing will be copied.

Try:

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

Reference:

https://stackoverflow.com/questions/30182538/why-can-not-i-copy-a-slice-with-copy-in-golang

https://golang.org/ref/spec#Appending_and_copying_slices

No comments: