liveBook · Manning

@view

As explained in Julia as a Second Language

@view is a Julia macro that transforms an array slice expression into a non-copying view of the selected data.

Array slicing normally creates a copy. That is useful when the selected data should be independent, but repeatedly copying large slices inside a tight loop can hurt performance. @view creates a non-copying view: the selected elements remain connected to the original array. section 14.4 section 14.7

Share data without copying

julia> A = [8, 1, 2, 7] julia> B = @view A[3:end] 2-element view(::Vector{Int64}, 3:4) with eltype Int64: 2 7 julia> B[2] = 1331 1331 julia> A 4-element Vector{Int64}: 8 1 2 1331 Changing B changes the corresponding element of A because B refers to A's selected data. By contrast, B = A[:] produces an independent copy.

The same idea applies to multidimensional arrays. Use ordinary indexing to select rows, columns, or submatrices, then place @view before the slice when the result should reference the original matrix rather than copy its elements. section 14.4

How Julia as a Second Language covers it

How deep it goes
Explains copy-versus-reference behavior with runnable one-dimensional examples and extends the idea to matrix slicing.
Examples
Uses copied and viewed vector slices, mutation through a view, and matrix row, column, and element indexing.
What it assumes
Assumes familiarity with Julia arrays, indexing, ranges, and ordinary slice-copy behavior.
What you can do after
Apply it via Julia's @view macro to create slices that reference selected elements in an existing array.
How it connects
Connects array slicing with arrays, matrices, indexing, and multidimensional data selection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.