在传统的面向对象语言(例如Java)中,可以通过从重写版本的超类调用原始方法来"扩展"继承类中方法的功能,例如:
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!");
}
}
如您所见,在Java中,我可以使用super
关键字从超类调用原始版本.我能够获得遗传特征的等效行为,但在为 struct 实现特征时却不行.
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"
}
因此,在继承特性的情况下,调用原始默认实现没有问题,但是,在实现 struct 时使用相同的语法会表现出不同的行为.这是铁 rust 内部的问题吗?有办法吗?还是我错过了什么?