JULIA / CHAPTER 04
Views, copies, and array ownership
IntermediateMake mutation and indexing boundaries visible.
By the end of this chapter
- Distinguish a slice copy from a view
- Trace changes through shared array storage
- Use indexing interfaces instead of assuming array origins
The idea
Ordinary range indexing of an array creates a new array containing the selected elements. A view instead describes part of the original storage. Changing an element through that view changes the parent array, which is useful for processing a window without copying but creates an ownership obligation. Decide whether a function receives an independent working copy or permission to modify its caller’s data.
Generic array code should also respect the indexing interface. Use axes or eachindex when the algorithm does not specifically require ordinary one-based dense arrays. A view can have a different shape or stride from a contiguous copy, so avoiding a copy is not automatically the fastest choice for repeated computation. First establish correct aliasing behavior, then measure representative workloads.
x = [1, 2, 3]
v = @view x[2:3]
v[1] = 9
y = x[2:3]
y[2] = 8
println(join(x, ","))
println(join(y, ","))1,9,3 9,8
The view shares x’s storage. The ordinary slice y has its own element storage, so its second assignment does not change x.
Try it yourself
Write a function that normalizes a selected view in place and document which caller-owned elements change.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING