Is there any way for a (mutable) struct to inherit fields from others?
For example, what I’m trying to do is:
mutable struct Parent
foo
bar
end
mutable struct Child <: Parent
end
and use child = Child(); child.foo = 1 (struct field inheritance).
However, an error was raised from the above code: invalid subtyping in definition of Child.
Nope, Julia doesn’t let you inherit from concrete types. Only abstract types can have subtypes. That said, usually what you want to do here is just have
@xiaodai@Oscar_Smith
Can you give me a more specific example to inherit “fields” from other struct?
Or, is it impossible in Julia? Should I write all individual fields manually?
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.
maybe i am not sure. maybe someone will point the way. But this pattern is not that common in Julia I would guess. You can acheive what u want (what u really want functionally, not aesthetically) using more Julian ways I would guess.
This package https://github.com/rjplevin/Classes.jl can help emulate something like what you’re asking for, but I would keep in mind that this is not usually the right way to do things in Julia. Using abstract types and method dispatch would be the recommended solution that leads to clearer / faster / more “Julian” code.
Many people using Julia give advices like you.
Unfortunately, I cannot find a both easy (to me) and Julian way to write codes although I’ve spent long time here.
I’ll read the post you suggested again and think about it deeply.
Thank you all!
@xiaodai
I’ve just read the book.
It’s helpful, and (probably) summarises the above stuffs.
+) I rethink that the feature I needed is REALLY necessary for me.
Great!