In traditional object-oriented languages (e.g. Java), it is possible to "extend" the functionality of a method in an inherited class by calling the original method from the super class in the overridden version, for example:
class A {
public void method() {
System.out.println("I am doing some serious stuff!");
}
}
class B extends A {
@Override
public void method() {
super.method(); // here we call the original version
System.out.println("And I'm doing something more!");
}
}
As you can see, in Java, I am able to call the original version from the super class using the super
keyword. I was able to get the equivalent behavior for inherited traits, but not when implementing traits for structs.
trait Foo {
fn method(&self) {
println!("default implementation");
}
}
trait Boo: Foo {
fn method(&self) {
// this is overriding the default implementation
Foo::method(self); // here, we successfully call the original
// this is tested to work properly
println!("I am doing something more.");
}
}
struct Bar;
impl Foo for Bar {
fn method(&self) {
// this is overriding the default implementation as well
Foo::method(self); // this apparently calls this overridden
// version, because it overflows the stack
println!("Hey, I'm doing something entirely different!");
println!("Actually, I never get to this point, 'cause I crash.");
}
}
fn main() {
let b = Bar;
b.method(); // results in "thread '<main>' has overflowed its stack"
}
So, in case of inherited traits, calling the original default implementation is no problem, however, using the same syntax when implementing structs exhibits different behavior. Is this a problem within Rust? Is there a way around it? Or am I just missing something?
Foo::method(self)
that calls the method on the specific type when called within the trait implementation for a struct calls the original implementation when called inside an inherited trait. Why is this? – Uchish