Copying Slices
Using copy()
The built-in copy function copies elements from a source slice into a destination slice, and unlike plain assignment, the two slices end up backed by completely separate memory afterward.
Example: Using copy()
package main
import "fmt"
func main() {
src := []int{1, 2, 3}
dst := make([]int, 3)
n := copy(dst, src)
fmt.Println("copied:", n, "dst:", dst)
}
Login to try C/C++/Java/PHP code in the editor
copy() Is Limited by the Shorter Slice
copy only transfers as many elements as fit in the smaller of the two slices -- if the destination is shorter than the source, the extra source elements are simply left out, with no error raised.
Note: Make sure the destination slice is at least as long as the source before copying, using make(len(src)) if needed.
Example: copy() Is Limited by the Shorter Slice
package main
import "fmt"
func main() {
src := []int{1, 2, 3, 4, 5}
dst := make([]int, 2)
n := copy(dst, src)
fmt.Println("copied:", n, "dst:", dst)
}
Login to try C/C++/Java/PHP code in the editor
Independence After Copying
Once copy() has run, modifying the destination slice never affects the source, and vice versa -- they are backed by entirely separate underlying arrays, which is the whole point of using copy instead of assignment.
Example: Independence After Copying
package main
import "fmt"
func main() {
original := []int{1, 2, 3}
duplicate := make([]int, len(original))
copy(duplicate, original)
duplicate[0] = 999
fmt.Println("original:", original)
fmt.Println("duplicate:", duplicate)
}
Login to try C/C++/Java/PHP code in the editor
- Assigning one slice variable to another ('b := a') expecting an independent copy, when it actually just shares the same underlying array.
- Calling copy(dst, src) with dst having fewer elements than src, and not realizing copy silently only copies up to len(dst).
- Forgetting copy() returns the number of elements actually copied, which is useful for verifying a full copy happened.
- copy(dst, src) copies elements from src into dst, up to the length of the shorter one.
- copy() is the way to create a truly independent slice, unlike plain assignment.
- The number of elements copied is limited by whichever slice (dst or src) is shorter.
- copy() returns an int: how many elements were actually copied.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: