By default, Julia will copy an array by reference. This means that if you change any values in the copy, the original will also change. For example:
> x = [1, 2, 3]
> z = x
> z[1] = 10
> print(x)
[10, 2, 3]
You can avoid this by using copy()
:
> x = [1, 2, 3]
> z = copy(x)
> z[1] = 10
> print(x)
[1, 2, 3]
However, this is only a shallow copy: it makes a copy of the data structure, but any objects within it are still copied by reference. Which is fine if it's an array of integer. But suppose instead you have an array of arrays:
> x = [[1, 2, 3], [4, 5, 6]]
> z = copy(x)
> z[1][1] = 10
> print(x)
[[10, 2, 3], [4, 5, 6]]
> z[2] = [7, 8, 9]
> print(x)
[[10, 2, 3], [4, 5, 6]]
You can see that the outer array structure was copied, but the inner arrays are still references to the originals. If you want to copy an array and it's contents, recursively, you need instead deepcopy()
:
> x = [[1, 2, 3], [4, 5, 6]]
> z = deepcopy(x)
> z[1][1] = 10
> print(x)
[[1, 2, 3], [4, 5, 6]]