Slice copy() function in Golang
A copy() function, the contents of a source slice are copied to a destination slice. A copy function also used internally, if element added into slice after the capacity of slice and slice will be increase by doubling the capacity of existing slice.
Copy slice using copy() function
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7 	var numbers = []int{1, 2, 3, 4, 5}
 8 
 9 	// print original slice
 10 	fmt.Println("Original slice : ", numbers)
 11 
 12 	sliceCopy := make([]int, len(numbers), (cap(numbers))*2)
 13 	// copy slice into sliceCopy
 14 	copy(sliceCopy, numbers)
 15 	fmt.Printf("\nCopied slice : %v", sliceCopy)
 16 }
In the above example, a slice is created and initialized with 5 elements. An original slice is printed using println() function. A slice is created using make() function by specifying a data type, length and capacity by referring an existing original slice.
A copy() function called by specifying a destination slice and source slice object that copies each elements into destination slice object. A copy of slice is printed using printf() function.
Output
 1 Original slice :  [1 2 3 4 5]
 2 
 3 Copied slice : [1 2 3 4 5]

Copy elements after appending elements

Copy slice
 1 package main
 2 
 3 import "fmt"
 4 
 5 func main() {
 6 
 7 	var numbers []int
 8 
 9 	// length capacity of slice
 10 	fmt.Printf("Length = %d, and Capacity = %d", len(numbers), cap(numbers))
 11 
 12 	fmt.Printf("\nSlice : %v", numbers)
 13 
 14 	numbers = append(numbers, 10)     // appending new element
 15 	numbers = append(numbers, 20, 30) // appending multiple elements
 16 	fmt.Printf("\nSlice : %v", numbers)
 17 
 18 	// after appending elements
 19 	fmt.Printf("\nLength = %d, and Capacity = %d", len(numbers), cap(numbers))
 20 
 21 	sliceCopy := make([]int, len(numbers), (cap(numbers))*2)
 22 
 23 	// copy slice into sliceCopy
 24 	copy(sliceCopy, numbers)
 25 	fmt.Printf("\nCopied slice : %v", sliceCopy)
 26 }
In the above example, we have define empty slice and appending 3 elements in the slice. The size and capacity of slice is printed using print statement. A define slice is copied into the sliceCopy using copy function by providing source and destination slice. It expect first slice as destination slice and second is source slice.
Output
 1 Length = 0, and Capacity = 0 // initial copy and capacity
 2 Slice : [] // initial element of slice
 3 Slice : [10 20 30] // slice after appending elements
 4 Length = 3, and Capacity = 3 // length and capacity after appending elements
 5 Copied slice : [10 20 30] // content of copied slice
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us