How to Copy Slice in Go: Simple Syntax and Examples
copy function, which copies elements from a source slice to a destination slice. You need to create a destination slice with enough length before copying to avoid overwriting or errors.Syntax
The copy function in Go copies elements from a source slice to a destination slice. Its syntax is:
copy(destinationSlice, sourceSlice)
Here, destinationSlice is the slice where elements will be copied to, and sourceSlice is the slice from which elements are copied. The function returns the number of elements copied, which is the minimum length of the two slices.
n := copy(dest, src)
Example
This example shows how to copy a slice of integers from one slice to another. It creates a destination slice with the same length as the source slice and uses copy to duplicate the elements.
package main import "fmt" func main() { src := []int{1, 2, 3, 4, 5} dest := make([]int, len(src)) n := copy(dest, src) fmt.Println("Copied elements count:", n) fmt.Println("Source slice:", src) fmt.Println("Destination slice:", dest) }
Common Pitfalls
A common mistake is to copy into a nil or zero-length slice, which results in no elements copied. Also, if the destination slice is smaller than the source, only part of the source is copied. Always create the destination slice with enough length to hold the copied elements.
package main import "fmt" func main() { src := []int{10, 20, 30} var dest []int // nil slice n := copy(dest, src) fmt.Println("Copied elements count with nil dest:", n) dest = make([]int, 2) // smaller length n = copy(dest, src) fmt.Println("Copied elements count with smaller dest:", n) fmt.Println("Destination slice after partial copy:", dest) }
Quick Reference
| Concept | Description |
|---|---|
| copy(dest, src) | Copies elements from src to dest, returns number copied |
| make([]T, len(src)) | Create destination slice with length equal to source |
| Partial copy | If dest shorter, only part of src is copied |
| Nil or zero-length dest | No elements copied, copy returns 0 |