The function syntax is as shown:
The function takes the destination and the source slice as the argument. As mentioned, it returned the number of elements copied.
The number of elements is determined by the minimum length of the source and destination slice. This is regardless of argument overlap.
Copy Slice into Another Slice
The example below illustrates how to copy a slice into another slice.
import "fmt"
funcmain() {
slice_1 := []int{1, 2, 3, 4, 5}
slice_2 := make([]int, 3)
fmt.Println("Before(slice_1): ", slice_1)
fmt.Println("Before(slice_2): ", slice_2)
// copy
copied_elements := copy(slice_2, slice_1)
fmt.Println("After(slice_1): ", slice_1)
fmt.Println("After(slice_2): ", slice_2)
fmt.Println("Elements copied: ", copied_elements)
}
The above code should return an output as shown:
Before(slice_2): [0 0 0]
After(slice_1): [1 2 3 4 5]
After(slice_2): [1 2 3]
Elements copied: 3
Notice the number of elements copied is determined by the minimum length of the source or destination slice. In our example, the minimum length is 3 as determined by slice_2.
Copy String into Byte Slice.
We know in Go, a string is basically a slice of bytes. Hence, it should be possible to copy a string into a byte slice.
Consider the example below:
import "fmt"
funcmain() {
str := "hello"
byte_slice := make([]byte, 10)
copied_elements := copy(byte_slice, str)
fmt.Println("Elements Copied: ", copied_elements)
fmt.Println("str: ", str)
fmt.Println("Byte Slice: ", byte_slice)
}
The above should copy the string into the byte slice. The resulting output is as:
str: hello
Byte Slice: [104 101 108 108 111 0 0 0 0 0]
Conclusion
In this article, we learnt how to use the copy function. This allows us to copy elements from a source slice to a specified destination. We can also copy a string to a byte slice as shown in the examples.
Thanks for reading!