Currently, the Indexing interface is composed of 4 functions:
However, among these functions, there is not one that returns the valid indexes of the indexable object.
In its documentation, it is shown that the eachindex function is related to AbstractArray. But I think it could be more generic and encompass all indexable objects.
Example
In this case, let’s use the same example from the documentation:
struct Squares
count::Int
end
function Base.getindex(S::Squares, i::Int)
1 <= i <= S.count || throw(BoundsError(S, i))
return i*i
end
Base.firstindex(S::Squares) = 1
Base.lastindex(S::Squares) = S.count
squares = Squares(100)
With only these methods implemented, the eachindex
function will not work:
julia> squares[50]
2500
julia> for s in eachindex(squares)
println(s)
end
ERROR: MethodError: no method matching keys(::Squares)
Closest candidates are:
keys(::OrderedCollections.OrderedSet) at C:\Users\Dev01\.julia\packages\OrderedCollections\PRayh\src\ordered_set.jl:95
keys(::Test.GenericArray) at C:\Users\Dev01\AppData\Local\Programs\Julia-1.8.1\share\julia\stdlib\v1.8\Test\src\Test.jl:1936
keys(::Tuple) at tuple.jl:71
...
Stacktrace:
[1] eachindex(itrs::Squares)
@ Base .\abstractarray.jl:282
[2] top-level scope
@ .\REPL[2]:1
However, other indexable objects that are not subtypes of AbtractArray
support the eachindex
function, such as Dict
:
julia> d = Dict(:a => 1, :b => 2)
Dict{Symbol, Int64} with 2 entries:
:a => 1
:b => 2
julia> for i in eachindex(d)
println(d[i])
end
1
2