C++ allows class subtyping, which is really convenient because you can use functions implemented for the base class with the derived class. Rust doesn't appear to have anything like that. The feature seems to have been available at some point, but has been removed since. Is this not possible in Rust? If so, are there any plans to have this feature?
What I want to do is define a struct that inherits from another struct, which in C++ would look like:
struct Base {
int x;
int y;
void foo(int x, int y) { this->x = x; this->y = y; }
}
struct Derived: public Base {
...
}
void main() {
Derived d;
d.foo();
}
The way I see it, in Rust you have to write something like this in order to make the same functionality available for all 'derived' structs:
struct Base<T> {
x: i32,
y: i32,
derived: T
}
impl<T> Base<T> {
fn foo(&mut self, x: i32, y: i32) {
self.x = x;
self.y = y;
}
}
I think doing an impl<T> for Base<T>
will produce a ton of copies of the same function, so composition isn't really an option.
I should probably point out that the implementation above was chosen for the simple reason that it allows a safer version of upcasting, which I need to do anyway.