Type inference on associated type

I'm having difficulties on finding out why type inference on the following code fails.

trait Main {
    type Sub: Sub<Main = Self>;
}

trait Sub {
    type Main: Main<Sub = Self>;
}

struct X;
struct Y;

impl Main for X {
    type Sub = Y;
}

impl Sub for Y {
    type Main = X;
}

/* this works
fn foo<M, S>(_: &S)
where
    M: Main<Sub = S>,
    S: Sub<Main = M>,
{}
*/

  // this does not work
fn foo<M: Main>(_: &M::Sub) {}
 

fn main() {
    foo(&Y);
}

Playground

The where clause on the working version is clearly redundant, there could only be one Main type M where M::Sub == S. Is this a bug?

Not necessarily a “bug”, but more if a limitation of type inference in the compiler as it stands. There’s definitely room for improvement; I can imagine that code like this will eventually no longer fail to compile at some point in the future. For now, calling the alternate version of foo would require explicitly calling foo::<X>(&Y) in order to work. In this particular case, you could probably just rewrite your function to be

fn foo<S: Sub>(_: &S) {}

instead. (If you needed M inside of that function, use S::Main now.)

Nice to hear there's no logic error on my side. Hope this will be allowed someday.

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.