Golang: Deep and Shallow Copy a Slice

Claire Lee
2 min readNov 18, 2022

--

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.

deep and shallow copy a slice

Deep Copy

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

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

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.

--

--

Claire Lee
Claire Lee

Responses (1)