# Field overloading to flatten struct composition?

**URL:** https://discourse.julialang.org/t/field-overloading-to-flatten-struct-composition/9325
**Category:** General Usage
**Created:** [February 25, 2018, 10:45pm UTC](https://discourse.julialang.org/t/field-overloading-to-flatten-struct-composition/9325 "2018-02-25T22:45:52Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![greg\_plowman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/greg_plowman/32/8100_2.png) [@greg\_plowman](https://discourse.julialang.org/u/greg_plowman)
#### Post date: [February 25, 2018, 10:45pm UTC](https://discourse.julialang.org/t/field-overloading-to-flatten-struct-composition/9325/1 "2018-02-25T22:45:52Z")

</div>

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?

```julia
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

```

---

<div class="post-metadata">

### Author: ![Nosferican](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nosferican/32/9275_2.png) [@Nosferican](https://discourse.julialang.org/u/Nosferican)
#### Post date: [February 26, 2018, 6:40am UTC](https://discourse.julialang.org/t/field-overloading-to-flatten-struct-composition/9325/2 "2018-02-26T06:40:52Z")

</div>

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.
