rust-lang / rust-lang/rust

"type annotations needed" on associated type in trait of unknown type should point to that unknown type

Open
#142,334 2 comments 1 reaction 1 assignee View on GitHub

@xizheyin is already working on this.

Since Jun 11, 2025.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
struct Foo;
impl Foo {
    fn method(&self) {}
}

trait Trait {
    type Assoc;
}
impl Trait for i32 {
    type Assoc = Foo;
}

fn get_assoc<T: Trait>(_: T) -> T::Assoc {
    unimplemented!()
}

fn conjure<T>() -> T {
    unimplemented!()
}

fn main() {
    let arg = conjure();  // This should be an i32
    get_assoc(arg).method();
}
Current output
error[E0282]: type annotations needed
  --> src/main.rs:23:5
   |
23 |     get_assoc(arg).method();
   |     ^^^^^^^^^^^^^^ cannot infer type

For more information about this error, try `rustc --explain E0282`.
error: could not compile `playground` (bin "playground") due to 1 previous error
Desired output
Something that points to `arg` or `conjure`
Rationale and extra context

Someone ran into this diagnostic in https://users.rust-lang.org/t/cannot-infer-type-of-vec-of-mpsc-sender/130579, and assumed that they had to annotate the type returned from get_assoc.

The above code is minimized to be self-contained. The original code which produced this issue was less obvious, since it involved the SliceIndex trait internally used to implement Vec indexing, as follows:

fn conjure<T>() -> T {
    unimplemented!()
}

struct Foo;
impl Foo {
    fn method(&self) {}
}

fn main() {
    let data: Vec<Foo> = vec![];
    let index = conjure();  // This should be a usize
    data[index].method();
}
error[E0282]: type annotations needed
  --> src/main.rs:13:5
   |
13 |     data[index].method();
   |     ^^^^^^^^^^^ cannot infer type

For more information about this error, try `rustc --explain E0282`.
error: could not compile `playground` (bin "playground") due to 1 previous error
Other cases

Rust Version
Reproducible on the playground with 1.89.0-nightly (2025-06-10 1677d46cb128cc8f285d)
Anything else?

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.