Learn how to use copy function in Golang
In this article, you are going to learn about how to use copy function in the Go language.
In Go language, you can copy one slice into another slice. To do so, you need to use the copy() function. This function is provided by Go-builtin packages. It simply takes two slices that is dst and src and data are being copied from src to dst. Let’s see the syntax of copy() function first in the below:
func copy(dst, src []Type) int
Here, dst stand-in-for destination slice and src stand-in-for source slice. It allows you to copy the number of elements. Let’s see an example of copy() function to make things more clear:
package main
import "fmt"
func main() {
// Creating slices
slice1 := []int{12, 15, 23, 26, 33, 38, 44, 48, 55, 60}
slice2 := make([]int, 6)
// Before copying
fmt.Println("Slice_1:", slice1)
fmt.Println("Slice_2:", slice2)
// Copying the slice
copy := copy(slice2, slice1)
fmt.Println("Copied Slice:", slice2)
fmt.Println("Total number of copied elements:", copy)
}
// Output:
// Slice_1: [12 15 23 26 33 38 44 48 55 60]
// Slice_2: [0 0 0 0 0 0]
// Copied Slice: [12 15 23 26 33 38]
// Total number of copied elements: 6
Here, you can see that we have declared two slices as slice1 and slice2. before using the copy() function the elements of slice2 were 0 and we have copied the first 6 elements from slice1 to slice2 by using the copy() function. As we have defined the length of slice2 to 6, it is not allowed to copy more than 6 elements from slice1.
You can also use the copy() function for the strings of a slice to another. See the below code example:
package main
import "fmt"
func main() {
// Creating slices
slice1 := []string{"Alex", "Deven", "Rohit", "Rathore", "Ricky"}
slice2 := make([]string, 3)
// Before Copying
fmt.Println("Slice_1: ", slice1)
fmt.Println("Slice_2: ", slice2)
// Copying the slice
Copy := copy(slice2, slice1)
fmt.Println("Copied Slice: ", slice2)
fmt.Println("Number of elements copied: ", Copy)
}
// Output:
// Slice_1: [Alex Deven Rohit Rathore Ricky Virat]
// Slice_2: [ ]
// Copied Slice: [Alex Deven Rohit Rathore]
// Number of elements copied: 4
Here, we have copied slice1 elements into slice2. Before copying, the elements of slice2 was empty and when we used copy() function and set the length 4 slice2 has copied first four elements from the slice1.
This is how you can use copy() function and can copy elements of one slice to another in Go language.