Skip to content

@view vs @views with scalar indexing #23759

@nalimilan

Description

@nalimilan

Currently @view always returns a SubArray, even when indexing with a scalar:

julia> x = 1:3
1:3

julia> @view x[1]
0-dimensional view(::UnitRange{Int64}, 1) with eltype Int64:
1

OTOH, @views returns the element when indexing with a scalar (as documented):

julia> @views x[1]
1

The behavior of @views sounds more consistent with plain getindex, and generally more useful. Rather than changing @view, @mbauman suggested deprecating it in favor of @views.

See #23051 (comment) for an example where the behavior of @views was more natural (but participant to the discussion seemed to be aware of its existence, so we ended up checking the index type manually).

(More radically, one could wonder whether view itself should behave like getindex when indexing with a scalar, and return the element rather than a view. Though that would be problematic if the goal was to mutate the parent array.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    arrays[a, r, r, a, y, s]

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions