Trying to understand how getindex works with vectors

I am trying to track down the functions that are being called when I’m evaluating

julia> A = 1:4
1:4

julia> A[A .> 2]
2-element Array{Int64,1}:
 3
 4

This starts with

function getindex(A::AbstractArray, I...)
    @_propagate_inbounds_meta
    error_if_canonical_getindex(IndexStyle(A), A, I...)
    _getindex(IndexStyle(A), A, to_indices(A, I)...)
end

so I call Base._getindex and find

julia> I = (A .> 2,);

julia> Base._getindex(IndexStyle(A), A, to_indices(A, I)...)
2-element Array{Int64,1}:
 3
 4

so far so good. Now I go one level deeper.

@inline function _getindex(l::IndexStyle, A::AbstractArray, I::Union{Real, AbstractArray}...)
    @boundscheck checkbounds(A, I...)
    return _unsafe_getindex(l, _maybe_reshape(l, A, I...), I...)
end

so I try calling _unsafe_getindex.

julia> l = IndexStyle(A)
IndexLinear()

julia> Base._unsafe_getindex(l, Base._maybe_reshape(l, A, I...), I...)
4-element Array{Int64,1}:
 0
 0
 1
 1

Eh? What happened here? Why does this not match the value returned by _getindex?

You’re missing

to_indices(A, I)

between _getindex and and _unsafe_get_index (you included it between getindex and _getindex)

2 Likes