-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Description
The Rust Reference says:
the syntax
Circle : Shape
means that types that implementCircle
must also have an implementation forShape
Traditionally this is accomplished by adding an implementation to the underlying struct, and thus the trait Circle
can only be applied to structs that supply an implementation for Shape
.
However, I think it is very often useful (including in the example in the reference) to allow the trait to supply the supertrait implementation all by itself. In the reference example, does it really make sense for every struct : Circle
to provide its own implementation of area
? No. The area of a circle is always π*r^2.
Notably, it is still true that "types that implement Circle
must also have an implementation for Shape
." The difference is whether this implementation is supplied by each struct separately, or by Circle
itself. The latter is better DRY.
Proposed syntax:
trait Shape { fn area(&self) -> f64;}
trait Circle : Shape {
fn radius(&self) -> f64;
fn area(&self) -> f64 { //here we supply an implementation for Shape
self.radius().powf(2.0) * 3.14
}
}
struct MyCircle;
//impl Shape for MyCircle not required since all Circles are known to have an implementation for Shape.
impl Circle for MyCircle { fn radius (&self) -> f64 { 2.0 } }
fn main() {
let b = MyCircle;
println!("{}",b.area());
}