Struct with array and dict of symbols: index array by symbol


#1

I have defined a struct:

struct State{T} <: AbstractArray{T,1}
    fields::Dict{Symbol, UnitRange{Int64}}
    arr::Array{T}
end

that might be initialized by something like

state0 = State(Dict([(:r, 1:3), (:v, 4:6)]), [10; 11; 12; 13; 14; 15])

I want to be able to do state0[:r] and get back [10; 11; 12].

I’ve tried defining

Base.getindex(S::State{T}, ind::Symbol) where {T} = S.arr[S.fields[ind]]

but I get ERROR: ArgumentError: invalid index: r.

Any fixes or suggestions on how to do this?


#2

I literally copied your code and got:

julia> state0[:r]
3-element Array{Int64,1}:
 10
 11
 12

#3

Wow, you’re right. I’m not sure what the problem was - I had already tried restarting the REPL, but I did so again and now it works.