Using rust 1.2.0
Problem
I'm still in the process of learning Rust (coming from a Javascript background) and am trying to figure out if it is possible for one struct StructB
to extend an existing struct StructA
such that StructB
has all the fields defined on StructA
.
In Javascript (ES6 syntax) I could essentially do something like this...
class Person {
constructor (gender, age) {
this.gender = gender;
this.age = age;
}
}
class Child extends Person {
constructor (name, gender, age) {
super(gender, age);
this.name = name;
}
}
Constraints
StructA
is from an externalcargo
package that I have no control over.
Current Progress
I found this blog post on single-inheritance which sounds like exactly what I need.
But trying to implement it resulted in this error message error: virtual structs have been removed from the language
. Some searching later and I found out that it had been implemented and then removed per RFC-341 rather quickly.
Also found this thread about using traits, but since StructA
is from an external cargo package I don't think it is possible for me to turn it into a trait.
So what would be the correct way to accomplish this in Rust?
Rust does not have struct inheritance of any kind. If you want
StructB
to contain the same fields asStructA
, then you need to use composition.Also, to clarify, traits are only able to define methods and associated types; they cannot define fields.
If you want to be able to use a
StructB
as aStructA
, you can get some of the way there by implementing theDeref
andDerefMut
traits, which will allow the compiler to implicitly cast pointers toStructB
s to pointers toStructA
s:There is nothing that exactly matches that. There are two concepts that come to mind.
Structural composition
You can simply embed one struct into another. The memory layout is nice and compact, but you have to manually delegate all the methods from
Person
toChild
or lend out a&Person
.Traits
You can combine these two concepts, of course.
As DK. mentions, you could choose to implement
Deref
orDerefMut
. However, I do not agree that these traits should be used in this manner. My argument is akin to the argument that using classical object-oriented inheritance simply for code reuse is the wrong thing. "Favor composition over inheritance" => "favor composition overDeref
". However, I do hold out hope for a language feature that enables succinct delegation, reducing the annoyance of composition.