Is this a known issue/limitation in associated types?

⚓ Rust    📅 2025-08-30    👤 surdeus    👁️ 2      

surdeus

I tried to make this example as minimal as I could. It seems very clear that within the impl Property for MyProperty<T>, Self::State should always be the same type as MyState, but the compiler doesn't seem to know that. Reframing the trait as T: HasStateFor<Property> makes the error go away. Does anyone know what's going on?

use std::marker::PhantomData;

trait CanGetStateFrom<T>: Property {
    fn get_state(input: &mut T) -> &mut Self::State;
}

trait Property {
    type State;
    fn update_state<T>(state_source: &mut T) where Self: CanGetStateFrom<T>;
}

struct MyProperty<T> {
    _phantom: PhantomData<T>,
}

struct MyState {
    field: u32,
}

impl<T> CanGetStateFrom<MyState> for MyProperty<T> {
    fn get_state(input: &mut MyState) -> &mut Self::State {
        input
    }
}

impl<T> Property for MyProperty<T> {
    type State = MyState;
    
    fn update_state<T2>(state_source: &mut T2) where Self: CanGetStateFrom<T2> {
        let state = Self::get_state(state_source);
        state.field += 1;
    }
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0609]: no field `field` on type `&mut <MyProperty<T> as Property>::State`
  --> src/lib.rs:31:15
   |
31 |         state.field += 1;
   |               ^^^^^ unknown field

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

1 post - 1 participant

Read full topic

🏷️ Rust_feed