Copying the elements of a slice to another slice is straightforward in Go, but it should be done using the builtin
append functions. If you simply assign an existing slice to a new variable, the slice will not be duplicated.
Both variables will refer to the exact same slice, so any changes to the slice’s value will be reflected in all its references. This is also true when passing a slice to a function since slices are passed by reference in Go.
To clone a slice without affecting the original, the
copy function can be used as shown below:
copy function takes the destination slice as the first argument and the source slice as the second, and both slices must be of the same type. The return value of
copy is the number of elements that was copied. If you don’t need this value, you can just ignore it as I’ve done above.
When using the
copy function, there one major thing to note: the lengths of both destination and source slices do not have to be equal. It will only copy up to the smaller number of elements. So if you attempt to copy to an empty or nil slice, nothing will be copied.
append function may also be used to copy a slice in Go. Here’s how:
In this case, the elements of
s1 is appended to a nil slice and the resulting slice is assigned to
s2. This method duplicates the entire slice regardless of the length of the destination unlike
copy above. Also note that the length of the destination slice may be truncated or increased according to the length of the source.
There are some edge cases with both methods discussed above. With
copy, the destination slice will not be
nil even if the source slice is
You can use the code below to fix this problem:
append, the destination slice will be
nil if the source slice is a non-nil slice with zero elements:
This can be fixed by creating a three-index subslice of the original slice and append to that instead while ensuring that the result does not share any elements with the source (by restricting the length and capacity of the subslice to be zero).
In this article, we looked at two different ways to clone a slice in Go, and also considered some edge cases associated with both methods. If you have any further contribution, feel free to leave a comment below.
Thanks for reading, and happy coding!