Slices in Go are dynamically-sized, flexible views into the elements of an array. They are much more versatile than arrays. When working with slices, it's crucial to know how to copy them efficiently, especially in performance-critical applications.
Basic Copying with the copy Function
The simplest way to copy slices in Go is by using the built-in copy function. This function takes two slices as arguments: the destination slice and the source slice. It copies data from the source slice into the destination and returns the number of elements copied.
package main
import "fmt"
func main() {
src := []int{1, 2, 3, 4, 5}
dest := make([]int, len(src))
n := copy(dest, src)
fmt.Println("Elements copied:", n) // Output: Elements copied: 5
fmt.Println("Destination slice:", dest) // Output: [1 2 3 4 5]
}
Intermediate: Copying Portions of a Slice
We can also copy a portion of a slice into another by specifying the required index ranges. This technique uses slicing operations before performing the copy.
package main
import "fmt"
func main() {
src := []int{1, 2, 3, 4, 5}
// Prepare destination slice with a specific length
dest := make([]int, 2)
// Copying a part of the source slice
copy(dest, src[1:3])
fmt.Println("Partially copied destination slice:", dest) // Output: [2 3]
}
Advanced: Creating Custom Copy Functions
Sometimes, you may need more control over how elements are copied, for example, by applying transformations or dealing with complex data structures. You can achieve this by writing a custom copy function.
package main
import "fmt"
func customCopy(dest, src []int, filterFunc func(int) bool) int {
var count int
for _, value := range src {
if filterFunc(value) {
dest[count] = value
count++
if count == len(dest) {
break
}
}
}
return count
}
func main() {
src := []int{1, 2, 3, 4, 5}
dest := make([]int, 3)
n := customCopy(dest, src, func(x int) bool {
return x%2 != 0
})
fmt.Println("Elements copied:", n) // Output: Elements copied: 3
fmt.Println("Filtered destination slice:", dest) // Output: [1 3 5]
}
In the above example, the custom copy function copies only odd numbers from the src slice to the dest slice. Such functions offer more flexibility for specific requirements.