Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Built-in Functions

Go copy() function

Reference for Go copy(): copy elements between slices or from a string into a byte slice, how many are copied, overlapping ranges and common mistakes.

copy() copies elements from a source slice into a destination slice and returns the number of elements copied. That number is the smaller of the two lengths, so copy never grows a slice and never panics because of a size mismatch.

It is the tool for making an independent copy of a slice (so changes no longer affect the original), for shifting elements inside a slice, and for filling part of a buffer. As a special case, the source can be a string when the destination is a []byte.

Go
dst := make([]int, 3)
n := copy(dst, []int{1, 2, 3, 4})
// n == 3, dst == [1 2 3]

Try it

Go Copy sizes and independence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Overlapping copies shift elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func copy(dst, src []Type) int
func copy(dst []byte, src string) int
Name Description
dst Destination slice. Elements from index 0 up to the number copied are overwritten.
src Source slice, or a string when dst is []byte.

Returns: min(len(dst), len(src)), the number of elements copied.

Edge cases: a nil or empty slice on either side copies nothing and returns 0. The two slices may overlap; the result is as if the source were first copied to a temporary buffer.

Usage notes

  • The destination length counts, not its capacity. copy(make([]int, 0, 10), src) copies nothing. Create the destination with make([]T, len(src)).
  • Shallow copy. Elements are copied by value; if they are pointers, slices or maps, both slices still share what those point to.
  • slices.Clone(s) is the shorter way to get an independent copy and keeps a nil slice nil. append([]T(nil), s...) also works.
  • Arrays: copy(arr[:], s) copies into an array via a slice of it. Assigning arrays with = copies the whole array already.
  • Overlap is safe, which is why copy(s[i:], s[i+1:]) is the classic way to delete an element.
  • No errors: if you need to know whether everything fit, compare the returned count with len(src).
  • Performance: it is implemented as a fast memory move, normally faster than a hand-written loop.