Home >Backend Development >Golang >How to Efficiently Create a Deep Copy of a Go Slice?
Creating a Deep Copy of a Slice in Go
When working with slices in Go, it's crucial to know how to create deep copies to ensure that changes made to one copy do not affect the original. One efficient approach is to leverage the built-in copy function.
Using the 'copy' Function
The copy function takes two slices as arguments, a destination slice dst and a source slice src. It copies elements from src to dst, even if the two slices overlap. The function returns the number of elements successfully copied.
Example:
cpy := make([]T, len(orig)) n := copy(cpy, orig)
In this example, a new slice cpy is created with the same length as the original slice orig. The copy function is then used to copy elements from orig to cpy, with n representing the number of elements copied.
Benchmarking Performance
To compare the performance of the copy function with the commonly used append method, a benchmark was conducted. The results showed that both methods have comparable performance:
BenchmarkCopy: 24724 ns/op BenchmarkAppend: 24967 ns/op
Considerations
It's important to note that while the copy function creates a deep copy of the slice values, it does not handle copying pointers or structures with pointer fields. These fields will still point to the same values as in the original slice.
The above is the detailed content of How to Efficiently Create a Deep Copy of a Go Slice?. For more information, please follow other related articles on the PHP Chinese website!