Copying Slices
Start with Copying Slices
Use the built-in copy function to copy elements between slices. It is the standard way to make an independent copy of slice contents.
What you’ll learn
- Explain the main purpose of copying slices.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
copy(destination, source) copies up to the smaller of the two lengths and returns the number of elements copied. The destination must already have enough length to receive the desired elements; spare capacity alone does not make indexes writable.
To clone a slice, allocate a destination with make([]T, len(source)) and then call copy. The destination and source can overlap; Go defines copy to handle overlapping regions correctly.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
original := []int{3, 6, 9}
independent := make([]int, len(original))
copied := copy(independent, original)
independent[0] = 30
fmt.Println("Copied:", copied)
fmt.Println("Original:", original)
fmt.Println("Independent:", independent)
}
Output
Copied: 3
Original: [3 6 9]
Independent: [30 6 9]Trace what the program does
The destination has length three, so copy transfers all three elements and returns 3. Changing independent[0] to 30 leaves the original slice unchanged because the destination was allocated separately.
Avoid common mistakes
copy(make([]int, 0, 3), source)copies zero elements because the destination length is zero.- Assigning
clone := originalcopies only the slice descriptor; it is not a deep element copy.
Try it yourself
Create a destination of length two and copy a three-element slice. Predict copy’s returned count.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Copying Slices in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.