Sobes.tech
Junior

What is the copy function in the Go programming language?

sobes.tech AI

Answer from AI

The copy function in Go is used to copy elements from a source slice (src) to a destination slice (dst).

It is defined as:

func copy(dst, src []Type) int
  • dst: The destination slice where elements will be copied to.
  • src: The source slice from which elements will be copied.
  • Returns: The number of elements copied, which is the minimum of the lengths of both slices (len(dst) and len(src)).

How the copy function works:

  • Copying occurs element by element, starting from index zero.
  • If dst is longer than src, only elements from src are copied.
  • If src is longer than dst, only elements up to the maximum length of dst are copied.
  • Slices can overlap. Copying elements in this case will be correct.

Example usage:

// Source slice
src := []int{1, 2, 3, 4, 5}
// Destination slice where we will copy
 dst := make([]int, 3)

// Copy elements from src to dst
n := copy(dst, src)

// Result: dst = [1 2 3], n = 3
// dst has length 3, so only the first 3 elements from src are copied.
// src = [1 2 3 4 5] remains unchanged.