Playground: Rust Playground
Code:
trait A{}
trait B{}
trait C{}
impl<T> A for T where T:B {}
impl<T> A for T where T:C {}
Playground: Rust Playground
Code:
trait A{}
trait B{}
trait C{}
impl<T> A for T where T:B {}
impl<T> A for T where T:C {}
What if T
implements both B
and C
? That's why it's not currently possible to do this.
Maybe should throw compile error when a struct implements both B
and C
? This is very helpful for us to eliminate some duplicate code.
That would make it impossible to implement a trait for a type, which is a backwards-compatible change. This has been thorough thought out by others in the past.
I don't think it's that easy to say that it couldn't be possible. All three traits are local to the same crate. It's already impossible for downstream users to implement both A
and B
if there's a blanket implementation
impl<T> A for T where T:B {}
I don't see a much different situation here for B
and C
if OPʼs code was to be allowed. And I personally hope that Rust will eventually allow patterns like that. But of course, please feel free to reference those instances of this question being “thorough[ly] thought out by others in the past” in case I'm missing something.
One tremendously useful aspect of allowing this: you could more or less think of B
and C
as different kinds of type-checked “templates” for implementing A
. This can save a lot of boilerplate code sometimes. And even if for some reason we can never support this with ordinary traits B
and C
, there could be use in a new feature that introduces some “type-checked trait implementation” templates for this reason. Kind of like multiple sets of default implementations for trait methods that you can choose from.
The rules around Type Alias Impl Traits have that the generic arguments must all be unique generic arguments from the surrounding scope for type-inference to work properly after type-checking. It's to avoid ambiguity
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.