Accessing properties/fields that are multiple properties/fields "deep"

Not sure exactly the best way to phrase the question. I have a bunch of custom types that get stacked together and I am trying use getproperty to get at things buried in these types.

struct Foo
a::Integer
b::Integer
end
struct Bar
c::Foo
end

Then

foo=Foo(1,2)
bar=Bar(foo)

I can access the a field of bar by doing

bar.c.a
1

But I get an error if I do

getproperty(bar,Symbol("c.a"))
ERROR: type Bar has no field c.a

What am I doing incorrectly?

I’m not entirely sure if this will help, but bar.c.a is essentially the same call as

getproperty(getproperty(bar, :c), :a)

i.e., recursive getproperty calls.

I realize I need a bit more context to explain what I want to do

the reason I dont want to do that is that I have things buried multiple layers ie a.b.c.d and I want to have a “clean up” function that goes to certain fields and sets them to nothing for managing memory and multithreading purposes. so something like this

a = MyDeepStruct
keep = [Symbol("b.c.d"),Symbol("e.f.g")]
function clean(a,keep)
     for s in keep
          setproperty!(a,s,nothing)
     end
end

something like that…

Check the Accessors.jl package out.

4 Likes