Trait inheritance is the same as a where clause, yes?

I just wanted to confirm my understanding:

Are these identical?

pub trait B : A {}

pub trait B where Self : A {}

Yes, the former is sugar for the where clause

I'd rather say the latter is a syntax sugar for the former, because they're treated differently from other forms of where clauses: Rust Playground

I also want to clear up that neither of your examples exhibit trait inheritance. This is because apparently Rust supports no such notion. All your examples mean is that in order to implement trait B, a type also must implement trait A.

Due to the fact that you can then leverage trait A in the definition of trait B, this is often mistakenly viewed as inheritance. Where this abstraction breaks down is when you try to upcast a &B to a &A, rust won't let you do this.

Note that if you add an impl A for &dyn B {} then the upcast will work, but it looks like Rust essentially considers &dyn B a fundamentally different type from dyn B or B.
In retrospect I guess that makes sense, as B isn't a type at all, and dyn B is a DST.

5 Likes

rust won't let you do this.

Note that trait object upcasting was defined in RFC 0401 long time ago but there have been no implementations. Currently alexreg is working on implementation: https://github.com/rust-lang/rust/pull/60900

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.