How to create a copy of a slice in Golang?

To create a copy of a slice in Golang, you can use the built-in copy() function. The copy() function takes two arguments: the destination slice and the source slice.

Here's an example of how to create a copy of a slice:

package main import "fmt" func main() { // Source slice source := []int{1, 2, 3, 4, 5, 6} // Creating a new slice with the same length as the source destination := make([]int, len(source)) // Copying the elements from the source to the destination copy(destination, source) // Modifying the destination slice destination[0] = 100 // Printing the source and destination slices fmt.Println("Source:", source) fmt.Println("Destination:", destination) }

Output:

Source: [1 2 3 4 5 6] Destination: [100 2 3 4 5 6]

In this example, copy(destination, source) copies the elements from the source slice to the destination slice. Changing elements in the destination slice does not affect the source slice, as they are now completely independent slices.