Skip to content

Allow a trait to implement its parent trait #1024

@drewcrawford

Description

@drewcrawford

The Rust Reference says:

the syntax Circle : Shape means that types that implement Circle must also have an implementation for Shape

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());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions