Generate a (mutable) struct which inherits others

Follow this example and just work thru it

mutable struct Parent
    foo
    bar
end

mutable struct Child
    parent::Parent
    foo # this is duplicated with parent
    notbar
end


parent = Parent(1, 2)

child = Child(parent, 3, 4)

child.bar # doesn't work

function Base.getproperty(child::Child, prop::Symbol)
    if prop in fieldnames(Parent) && !(prop in fieldnames(Child))
        return getfield(child.parent, prop)
    else
        return getfield(child, prop)
    end
end

child.bar # works now

child.foo # returns child value instead of parent value;

child.parent.foo # return parent's foo

This shows the underlying mechanism. If you do this pattern alot you can make it easier by using a macro to write those codes for you.

3 Likes