Partition trait implementation based on associated type of other trait

⚓ Rust    📅 2025-09-20    👤 surdeus    👁️ 9      

surdeus

Warning

This post was published 41 days ago. The information described in this article may have changed.

I want to implement a trait A for all implementers of another trait B, but I want to have different implementations based on the associated type of this other trait. This should be possible in theory since the associated type of a trait is unique for an implementer and therefore it should partition the implementers without overlap.

This is the code that does not compile:

struct S1;
struct S2;

trait A {
    type O;
}

trait B {}

impl<T> B for T where T: A<O = S1> {}
impl<T> B for T where T: A<O = S2> {}

I get this error when compiling:

error[E0119]: conflicting implementations of trait `B`
  --> src/lib.rs:11:1
   |
10 | impl<T> B for T where T: A<O = S1> {}
   | ---------------------------------- first implementation here
11 | impl<T> B for T where T: A<O = S2> {}
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation

For more information about this error, try `rustc --explain E0119`.
error: could not compile `playground` (lib) due to 1 previous error

Why is this not possible? Is there some fundamental problem or is it just a missing feature in the type checker? Is it somehow possible to achieve what I want (favorably on stable Rust)?

4 posts - 3 participants

Read full topic

🏷️ Rust_feed