Golang: Deep and Shallow Copy a Slice
Deep copy a slice using either the built-in copy or append function to get a duplicated slice. However, assign an existed slice to a new variable gets a shallow copy whose slice header points to the same backing array as the source slice.
Table of Contents
· Deep Copy
∘ copy built-in function
∘ append built-in function
· Shallow Copy
∘ assignment
Deep Copy
copy built-in function
- copy function copies elements from a source(src) slice into a destination(dst) slice.
func copy(dst, src []Type) int
Create a new empty slice with the same size of the src and then copy all the elements of the src to the empty slice.
Using the copy function, src and dst slices have different backing arrays. You can see the memory address of their backing array are different.
append built-in function
- append function appends elements to the end of a slice.
func append(slice []Type, elems ...Type) []Type
Append all the elements of the src to an empty slice to get a duplicate slice.
Using the append function, src and dst slices have different backing arrays. You can see the memory address of their backing array are different.
Shallow Copy
assignment
Assignment a existed slice to a new variable.
By assignment, the memory address of the backing array is the same for both of src and dst slices.
You can access the source code here.