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
anddst
.
As a special case, it’s legal to copy bytes from a string to a slice of bytes.
copy(dst []byte, src string) int
Rules:
Only the number of elements that both slices can accommodate will be copied (i.e., the minimum length of
dst
andsrc
).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:
The
src
slice has 5 elements:[1, 2, 3, 4, 5]
.The
dst
slice has a capacity of 3, so only the first 3 elements fromsrc
are copied.The
copy
function returns the number of elements copied, which is3
in this case.
Edge Cases:
Destination shorter than source: Only as many elements as the destination can hold are copied.
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!