rust-lang / rust-lang/rust

Compilation error seems to suggest that *more* references are needed

Open
#136,262 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Code
pub trait Trait {
    type E;
}

pub struct S<T: Trait> {
    pub v: T::E,
}

fn foo<T: Trait>(s: &mut [S<T>]) {
    let v = &s[0].v;
    let c = S { v };
    s[0] = c;
}
Current output
error[E0271]: type mismatch resolving `<T as Trait>::E == &<T as Trait>::E`
  --> src/lib.rs:11:17
   |
11 |     let c = S { v };
   |                 ^ expected `&<T as Trait>::E`, found associated type
   |
   = note:    expected reference `&_`
           found associated type `_`
help: consider constraining the associated type `<T as Trait>::E` to `&<T as Trait>::E`
   |
9  | fn foo<T: Trait<E = &<T as Trait>::E>>(s: &mut [S<T>]) {
   |                ++++++++++++++++++++++
Desired output
error[E0271]: type mismatch resolving `<T as Trait>::E == &<T as Trait>::E`
  --> src/lib.rs:11:17
   |
11 |     let c = S { v };
   |                 ^ expected `<T as Trait>::E`, found `&<T as Trait>::E`
   |
   = note:    expected associated type `_`
           found reference `&_`
Rationale and extra context

The error message seems to suggest that the compilation issue should be solved by making v "more of a reference", when in fact the opposite is needed.
This can be quite confusing.

Other cases

Rust Version
rustc 1.86.0-nightly (bf1b174e7 2025-01-28)
binary: rustc
commit-hash: bf1b174e7d0922fc549071b751ab96fc9ee9f6fe
commit-date: 2025-01-28
host: x86_64-unknown-linux-gnu
release: 1.86.0-nightly
LLVM version: 19.1.7
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.

Research direction

Reproduce the E0271 diagnostic from the Rust code in src/lib.rs using the reported rustc 1.86.0-nightly version. Start by tracing how the compiler formats the expected and found associated types for this mismatch. Done means the diagnostic no longer suggests adding an unnecessary reference and matches the requested ordering.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.