Copy overlapping slices
Copy overlapping slices
copy(dst, src) copies elements and returns the smaller of the two lengths. Source and destination may overlap. The destination length does not change.
package main
import "fmt"
func main() { src := []int{1, 2, 3} dst := make([]int, 2) n := copy(dst, src) fmt.Println(dst, n) empty := make([]int, 0, 3) fmt.Println(copy(empty, src), len(empty))}The destination has two visible elements. The empty destination has capacity but zero length, so nothing is copied. Allocate the desired length before copying.
Expected output:
[1 2] 20 0Shift elements in either direction
package main
import "fmt"
func main() { s := []int{1, 2, 3, 4} n := copy(s[1:], s[:3]) fmt.Println(s, n) t := []int{1, 2, 3, 4} copy(t, t[1:]) fmt.Println(t)}Overlapping copies work in both directions. The original source values are preserved for the operation. The duplicate at the end of t remains until overwritten or logically removed.
Expected output:
[1 1 2 3] 3[2 3 4 4]Try it locally
Given []int{10,20,30,40}, copy the tail to the front and reslice to the returned count. Print count and result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 05: Copy overlapping slices
Check the lesson objective before moving on.
How many elements does copy transfer when destination length is 2 and source length is 5?
Is overlapping slice copy supported?