How 'copy' built-in function works in Go

Photo by Chinmay B on Unsplash

How 'copy' built-in function works in Go

The copy built-in function in Go is used to copy elements from one slice to another. It is particularly useful when you need to duplicate or copy portions of a slice into another slice.

Syntax

copy(dst, src []T) int
  • dst: The destination slice where elements are copied to.

  • src: The source slice from which elements are copied.

  • T: The type of elements in the slices.

  • Return value: The function returns the number of elements that were copied, which is the minimum of the lengths of src and dst.

As a special case, it’s legal to copy bytes from a string to a slice of bytes.

copy(dst []byte, src string) int
💡
Remember! You can use copy function to create independent slices. This allows to avoid the problem of sharing the same underlying array when using the slice of slices operations.

Rules:

  • Only the number of elements that both slices can accommodate will be copied (i.e., the minimum length of dst and src).

  • The copy function works with any slice type, as long as both slices have elements of the same type.

Example:

package main

import "fmt"

func main() {
    // Source slice
    src := []int{1, 2, 3, 4, 5}

    // Destination slice with enough capacity
    dst := make([]int, 3)

    // Copying elements from src to dst
    numCopied := copy(dst, src)

    fmt.Println("Source slice:", src)                    // [1, 2, 3, 4, 5]
    fmt.Println("Destination slice after copy:", dst)    // [1, 2, 3, 4, 5] --> [0, 0, 0] --> [1, 2, 3]
    fmt.Println("Number of elements copied:", numCopied) // 3
}

Output:

Source slice: [1 2 3 4 5]
Destination slice after copy: [1 2 3]
Number of elements copied: 3

Explanation:

  1. The src slice has 5 elements: [1, 2, 3, 4, 5].

  2. The dst slice has a capacity of 3, so only the first 3 elements from src are copied.

  3. The copy function returns the number of elements copied, which is 3 in this case.

Edge Cases:

  1. Destination shorter than source: Only as many elements as the destination can hold are copied.

  2. Source shorter than destination: The copy will stop when all elements of the source have been copied.

package main

import "fmt"

func main() {
    src := []int{1, 2}          // [1, 2]
    dst := make([]int, 5)       // [0, 0, 0, 0, 0]
    numCopied := copy(dst, src) // 2
    fmt.Println("Dst:", dst)    // [1, 2, 0, 0, 0]
    fmt.Println("Number of copied elements", numCopied)
}

In this case, only 2 elements from src are copied into the first two positions of dst.

Benefits:

  • Efficient copying without needing a loop.

  • Works with slices of any type (integers, strings, structs, etc.).

That’s the basic idea of the copy function in Go!

References:

  1. How to use the copy function

  2. Go Blog: Slices Intro