This isn’t possible directly now.
However, RFC 1210: impl
specialization contains various aspects that will make this sort of behaviour work, for example, something like this should work:
trait Foo {
fn method(&self) { println!("default implementation"); }
}
trait Bar: Foo { ... }
partial impl<T: Bar> Foo for T {
default fn method(&self) { println!("Bar default"); }
}
Doing a super
call is explicitly mentioned as an extension to it and so won’t necessarily appear immediately, but may appear in future.
In the mean time, the approach generally used is to define a separate function for the default behaviour and call that in the default method, and then users can emulate the super::...
call by just calling that function directly:
trait Foo {
fn method(&self) { do_method(self) }
}
fn do_method<T: Foo>(_x: &T) {
println!("default implementation");
}
impl Foo for Bar {
fn method(&self) {
do_method(self);
println!("more");
}
}
That said, Rust favours composition over inheritance: designs that work well in Java can’t and shouldn’t be forced 1-to-1 into Rust.
Foo::method(self); // this apparently calls this overridden // version, because it overflows the stack
The qualified path syntax, Trait::method(value)
is sugar for <Type as Trait>::method(value)
where Type
is the type of value
(or, possibly, the type after dereferencing some number of times). That is, it’s calling the method on the specific type as you found out.