Skip to content

Rustc complains about not being able to infer the wrong type parameter #105797

Closed
@sfackler

Description

@sfackler

I tried this code:

trait ToFoo<T, W> {
    type Foo: Foo<W>;
    
    fn to_foo(value: T) -> Self::Foo;
}

trait Foo<W> {}

struct Fooer<T>(T);

impl<T, W> Foo<W> for Fooer<T> {}

struct ToFooer;

impl<T, W> ToFoo<T, W> for ToFooer {
    type Foo = Fooer<T>;
    
    fn to_foo(value: T) -> Self::Foo {
        Fooer(value)
    }
}

fn main() {
    let _foo = <ToFooer as ToFoo<_, _>>::to_foo(());
}

I expected to see this happen: The compiler complain that the W parameter of ToFoo couldn't be inferred.

Instead, this happened: It instead complains about T.

error[[E0282]](https://doc.rust-lang.org/stable/error-index.html#E0282): type annotations needed
  --> src/main.rs:24:16
   |
24 |     let _foo = <ToFooer as ToFoo<_, _>>::to_foo(());
   |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the trait `ToFoo`

For more information about this error, try `rustc --explain E0282`.

T should be inferred from the argument being passed to to_foo, but you get the same error message even if you explicitly specify it:

error[[E0282]](https://doc.rust-lang.org/stable/error-index.html#E0282): type annotations needed
  --> src/main.rs:24:16
   |
24 |     let _foo = <ToFooer as ToFoo<(), _>>::to_foo(());
   |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the trait `ToFoo`

For more information about this error, try `rustc --explain E0282`.

It successfully compiles when the second type parameter (i.e. W) is explicitly specified.

Meta

rustc --version --verbose:

rustc 1.66.0 (69f9c33d7 2022-12-12)
binary: rustc
commit-hash: 69f9c33d71c871fc16ac445211281c6e7a340943
commit-date: 2022-12-12
host: x86_64-unknown-linux-gnu
release: 1.66.0
LLVM version: 15.0.2

Same thing happens on nightly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions