How to use the copy function in Go

The copy() function in Golang copies the elements from a source slice to a destination slice and returns the number of elements copied.

Prototype

Parameters and return value

The copy() function accepts a destination slice and a source slice of variable lengths and the same type.

It is legal to copy string slice elements to a byte slice.

The copy() function returns the number of elements copied, equal to the minimum of the length of the source slice and destination slice.

For example, if the length of the source slice is 5 and the length of the destination slice is 8, the number of copied elements will be 5. Similarly, if the length of the source slice is 10 and the length of the destination slice is 8, the number of copied elements will be 8.

Examples

The following code demonstrates how to use the copy() function in Go:

Example 1

Example 1 creates a destination slice of length 4 and a source slice of length 3. As a result, only the first three elements of the destination slice are changed.

Example 2

Example 2 uses the same slice as the destination and source slice. The last two elements of the slice are copied onto the first two elements of the slice. As a result, the number of copied elements is 2.

package main
import "fmt"
func main() {
fmt.Println("---Example 1---")
// Example 1
// define s source slice
sourceSlice := []int{11,22,33}
// define a destination slic
destSlice := []int{44,55,66,77}
// call copy function
numberCopied := copy(destSlice, sourceSlice)
// display the destination slice
fmt.Println(destSlice)
// display the number of copied elements
fmt.Println("Number of elements copied:")
fmt.Println(numberCopied)
fmt.Println("---Example 2---")
// Example 2
// use the same slice as the source and destination slice
numberCopied = copy(destSlice, destSlice[2:])
// display the destination slice
fmt.Println(destSlice)
// display the number of copied elements
fmt.Println("Number of elements copied:")
fmt.Println(numberCopied)
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved