Compiler fails to recognise associated type bound

⚓ Rust    📅 2026-06-06    👤 surdeus    👁️ 1      

surdeus

I encountered the following weird situation (example is highly simplified, playground: Rust Playground):

pub trait A {
    type X: B<T = Self>;
    type Y: A<X = Self::Z>;
    type Z: B;
}

pub trait B {
    type T;
    
    fn with_t(self, t: Self::T);
}

pub fn comp<S: A>(m: S::Y, s: <S::Y as A>::X) {
    s.with_t(m)
}

I would have hoped that the compiler understands that <<S::Y as A>::X as B>::T is the same type as S::Y due to the constraint on A::X, but it seems like it does not:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/lib.rs:14:14
   |
14 |     s.with_t(m)
   |       ------ ^ expected `B::T`, found `A::Y`
   |       |
   |       arguments to this method are incorrect
   |
   = note: expected associated type `<<S as A>::Z as B>::T`
              found associated type `<S as A>::Y`
   = note: an associated type was expected, but a different one was found
note: method defined here
  --> src/lib.rs:10:8
   |
10 |     fn with_t(self, t: Self::T);
   |        ^^^^^^       -

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

The weird thing is that it works if I remove the <X = Self::Z> from A::Y which seems to bring the compiler on the wrong track. Any idea why this is happening and how I can fix this?

1 post - 1 participant

Read full topic

🏷️ Rust_feed