Field overloading to flatten struct composition?


#1

I was wondering whether composite type field overloading (introduced in 0.7) could be used to “flatten” access to composed data structures. There has been much discussion about inheritance vs composition, and I was hoping to use composition but access the fields directly, as if inherited.

An example probably helps explain what I mean.
The following works but is probably too slow. Is there a way to make this work efficiently?

struct Foo
    a::Int
    b::Int
end

struct Bar
    foo::Foo
    c::Int
    d::Int
end

function Base.getproperty(x::Bar, f::Symbol)
    if f in fieldnames(Foo)
        getfield(x.foo, f)
    else
        getfield(x, f)
    end
end

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

bar.a
bar.b
bar.c
bar.d

#2

That seems like a really bad idea. What if Foo and Bar share same fieldnames? If it makes sense in certain application, the correct design would be to make a good API with accessor methods.