In Julia, array slices create copies by default, not views. When you index an array using a range or a vector of indices (e.g., a[1:3] or a[[1, 2, 3]]), Julia returns a new array that contains copies of the selected elements. Modifying this new array does not affect the original array.
Here's an example to illustrate this behavior:
# Original array
a = [1, 2, 3, 4, 5, 6]
# Create a slice (which is a copy)
b = a[1:3]
# Modify the slice
b[1] = 10
# Check the original array
println(a) # Output: [1, 2, 3, 4, 5, 6]
# The original array 'a' remains unchanged.
As you can see, changing b[1] does not affect a[1], confirming that b is a separate copy.
If you want to create a view into the original array—so that changes to the view reflect in the original array—you can use the view function or the @view macro:
# Create a view of the array
v = view(a, 1:3)
# Alternatively, using the @view macro:
# v = @view a[1:3]
# Modify the view
v[1] = 10
# Check the original array
println(a) # Output: [10, 2, 3, 4, 5, 6]
# The original array 'a' is modified through the view.
In this case, changing v[1] directly affects a[1], since v is just a different way to access the same elements in memory.
Summary:
Default Slicing (a[1:3]): Creates a copy. Modifying the result does not affect the original array.
Using view (view(a, 1:3) or @view a[1:3]): Creates a view. Modifications affect the original array.
This behavior is consistent across Julia versions up to your knowledge cutoff in October 2023. Using views can be more memory-efficient, especially for large arrays, since it avoids copying data. However, be cautious when using views, as unintended modifications can occur to the original array.