A Slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Slice, you can copy one slice into another slice using the copy() function provided by the Go language. Or in other words, copy() function allows you to copy the elements of one slice into another slice.
func copy(dst, src Type) int
Here, dst represents the destination slice and src represents the source slice. It will return the number of elements copied that will be the minimum of len(dst) or len(src). Let us discuss with the help of the given example:
Slice_1: [58 69 40 45 11 56 67 21 65] Slice_2:  Slice_3: [0 0 0 0 0] Slice_4: [78 50 67 77] Slice:  Total number of elements copied: 0 Slice: [58 69 40 45 11] Total number of elements copied: 5 Slice: [58 69 40 45] Total number of elements copied: 4 Slice: [58 69 40 45 11 56 67 21 65] Total number of elements copied: 4
Explanation: In the above example we have four integer type slices and we perform copy operation on them:
- copy_1:= copy(slc2, slc1): Here, slc2 is the destination slice and slc1 is the source slice. Here, slc2 is the nil slice when we try to copy slc1 slice in slc2 slice, then copy method will return the minimum of length of source and destination slice which is zero for empty slice slc2.
- copy_2:= copy(slc3, slc1): Here, slc3 is the destination slice and slc1 is the source slice. Here, the slc3 slice is the empty slice, so when we try to copy slc1 slice into slc3 using copy() function it copies only 5 elements from the slc1 slice starting from index 0 because the length of this slice is 5, so it can not store elements greater than 5.
- copy_3:= copy(slc4, slc1): Here, slc4 is the destination slice and slc1 is the source slice. When we try to copy slc1 slice into slc4 slice using copy() function it copies only 4 elements in it starting from index 0. Because the length of the slc4 slice is 4, so it can not store elements more than 4.
- copy_4:= copy(slc1, slc4): Here, you might be confused after its output. See, slc4 has been updated in the above line of code. So now consider the updated values for slc4. So now slc4 has 4 elements and slc1 has 9 elements. So, the total number of elements that will be copied is 4.
Slice_1: [Geeks for Geeks GFG] Slice_2: [ ] Slice_1: [Geeks for Geeks GFG] Slice_2: [Geeks for Geeks] Number of elements copied: 3 Slice_1: [123geeks gfg Geeks GFG] Number of elements copied: 2
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.