![]() |
VOOZH | about |
In Go, a Slice is a variable-length sequence that can hold elements of the same type. You can’t mix different types of elements in a single slice. To copy one slice into another, Go provides a built-in function called copy(). This function allows you to duplicate the elements from one slice (the source) into another slice (the destination).
package main
import "fmt"
// Basic slice to be used in all examples
var source = []int{10, 20, 30, 40, 50}
func main() {
fmt.Println("Source Slice:", source)
}func copy(dst, src []Type) intcopy() FunctionHere’s how to copy the source slice into a destination slice using the copy() function:
Source: [10 20 30 40 50] Destination: [10 20 30 40 50] Elements copied: 5
destination using make() that can hold the same number of elements as the source slice.copy() function to copy the elements from the source slice to the destination slice. The copy() function returns the number of elements that were copied.You can copy slices manually using a loop.
for i := 0; i < len(source); i++ { destination[i] = source[i]}Example:
Source: [10 20 30 40 50] Destination: [10 20 30 40 50]
If you want to create a copy of a slice while initializing it, you can use a slice literal with the append() function.
destination = append(destination, source...)Example:
Source: [10 20 30 40 50] Destination: [10 20 30 40 50]
Note: Ensure that the destination slice is of equal or greater length than the source slice when using copy(); otherwise, the function will only copy up to the length of the destination slice.