copy
copy(dst, src) copies elements from src into dst and returns how many it copied: the minimum of the two lengths. It does not grow dst. Overlapping slices are safe.
Detailed Explanation
You have a window of a large buffer and you want a slice that does not keep the buffer alive. out := make([]T, len(window)); copy(out, window) does that. append([]T(nil), window...) does it too. copy is the built-in when the destination already exists.
Length, not capacity, decides the count. copy will not write past len(dst). A common mistake is dst := make([]int, 0, 8); copy(dst, src) which copies zero elements. Use make([]int, len(src)) when copy is the point, or append when growth is the point.
Overlap is defined. copy(s[1:], s) shifts left; copy(s, s[1:]) shifts right. The runtime uses a direction that does not corrupt the source. You do not need memmove vs memcpy here.
Strings into []byte. copy(buf, str) is allowed and copies bytes. It still stops at len(buf).
Arrays. You can copy between an array and a slice by slicing the array: copy(s, arr[:]). There is no copy that takes two arrays without slicing.
What it costs. copy is a memmove of n * sizeof(T) bytes. For large T that is a lot of bytes. For []byte it is the obvious fast path. Prefer copy over an element loop; the compiler and runtime already specialize it.
Code Examples
package main
import "fmt"
func main() {
src := []int{1, 2, 3}
dst := make([]int, len(src))
n := copy(dst, src)
fmt.Println(n, dst) // 3 [1 2 3]
dst[0] = 9
fmt.Println(src[0]) // 1 — independent
}func clipCopy(src []int) []int {
dst := make([]int, 0, 8)
copy(dst, src) // n == 0: dest length is 0
return dst
}
func right(src []int) []int {
dst := make([]int, len(src))
copy(dst, src)
return dst
}func shiftLeft(s []int) {
copy(s, s[1:])
s[len(s)-1] = 0
}Common Gotchas
`copy` does not grow the destination
a `len` of 0 copies nothing even if `cap` is large.
`copy` does not change `len`
if you `make([]T, 8)` and copy 3 elements, `len` is still 8 and the rest are zeros.
The return value is the number copied
ignore it only when you already know `len(dst) <= len(src)` or the reverse and you do not care about a short copy.
Overlap is safe
you can slide a slice on itself without a temporary.