Array copying creates another array with the same elements. The copy may duplicate only the element references, or it may recursively duplicate the objects stored inside the array.
You use it when a later mutation should not change the original array storage.
Problem
Given an array of length , create a new array such that:
for every valid index .
Algorithm
Copy each element into a new array.
copy_array(A):
n = length(A)
B = allocate(n)
for i from 0 to n - 1:
B[i] = A[i]
return BExample
Let
Copying produces:
| index | A | B |
|---|---|---|
| 0 | 8 | 8 |
| 1 | 3 | 3 |
| 2 | 5 | 5 |
| 3 | 1 | 1 |
| 4 | 9 | 9 |
Changing afterward does not change for value types.
Correctness
The algorithm allocates a new array of the same length as the input. It then visits every valid index and writes into . Therefore, every position in the output has the same value as the corresponding position in the input.
Since the backing storage is different, later changes to the array slots of do not overwrite the slots of .
Complexity
| operation | time |
|---|---|
| copy |
Space usage:
When to Use
Array copying is appropriate when:
- the original array must be preserved
- a function needs independent storage
- resizing requires moving elements
- snapshot-style behavior is needed
Be careful with shallow copies when elements are references. The array storage is copied, but the referenced objects may still be shared.
Implementation
def copy_array(a):
b = [None] * len(a)
for i in range(len(a)):
b[i] = a[i]
return bfunc CopyArray[T any](a []T) []T {
b := make([]T, len(a))
copy(b, a)
return b
}