How to copy a slice in Golang
Introduction
There are two ways to copy a slice in Golang. You can use the built-in copy
function or use the append
function.
1. The copy function
To copy a slice in Golang, you can use the built-in copy function. This function takes two arguments: the destination slice and the source slice. The copy function will copy the elements from the source slice to the destination slice.
The output of the program is:
If the destination slice is smaller than the source slice, the copy function will only copy the number of elements fitting the destination slice.
The output of the program is:
If the destination slice is larger than the source slice, the copy function will copy all the elements from the source slice and leave the remaining elements in the destination slice unchanged.
The output of the program is:
By default, the value of an uninitialized element in a slice is the zero value of the element type. In the example above, the zero value of an an integer is 0.
To make sure that you copy all the elements from the source, get the length of the source and use it to create the destination slice.
The output of the program is:
The copy function returns the number of elements copied. This value returned is used to check if the copy was successful.
The output of the program is:
2. The append function
To copy a slice in Golang, you can also use the append
function. This function takes two arguments: the destination slice and the source slice. The append
function will copy the elements from the source slice to the destination slice.
You need to spread the source slice using the ...
operator.
The output of the program is:
The downside of using the append
function is that it will allocate excess memory. So it is not recommended to use it for smaller slices.
3. Conclusion
In this article, we learned how to copy a slice in Golang. We learned that there are two ways to copy a slice in Golang; the copy
function and the append
function.