rust-lang / rust-lang/rfcs

Allow a trait to implement its parent trait

Open
#1,024 20 comments 39 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the Rust Reference traits example and the proposed syntax in this issue first. Compare the requested supertrait behavior with current Rust trait rules; done means a settled, implementable design for allowing Circle to provide Shape's implementation, with its interaction with implementing structs made explicit.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.