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
关键字调用超类的原始版本。我已经成功地为继承特性获得了等效行为,但在实现结构体特性时却无法这样做。
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"
}
因此,对于继承的特性,调用原始默认实现没有问题,但是在实现结构体时使用相同语法会产生不同的行为。这是 Rust 中的问题吗?有没有解决方法?还是我漏掉了什么?
Foo::method(self)
在结构体的特征实现中调用特定类型的方法时,当在继承的特征内部调用时,会调用原始实现。这是为什么呢? - faifaceBoo::method
方法,与Foo::method
方法不同。它仍然在特定类型上调用特定方法;我猜测你的测试代码没有覆盖Foo
上的method
方法,只有在Bar
上覆盖了。 - huon