rust-lang / rust-lang/rust

Detect call to `_::foo(&mut self)` confused with `_::foo(&self) -> Self`

Open
#159,486 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics D-confusing D-lack-of-suggestion D-newcomer-roadblock D-papercut T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Code
fn main() {
    let mut values = vec![3, 1, 2];
    let sorted = values.sort();
    println!("{}", sorted[0]);
    //~^ ERROR cannot index into a value of type `()`
}
Current output
error[E0608]: cannot index into a value of type `()`
 --> src/main.rs:4:26
  |
4 |     println!("{}", sorted[0]);
  |                          ^^^
  |
  = help: tuples are indexed with a dot and a literal index: `tuple.0`, `tuple.1`, etc.
Desired output
error[E0608]: cannot index into a value of type `()`
 --> src/main.rs:4:26
  |
2 |     let mut values = vec![3, 1, 2];
3 |     let sorted = values.sort();
  |                         ------ this method call modifies `values` in-place
4 |     println!("{}", sorted[0]);
  |                          ^^^
  |
note: `Vec::sort` takes `&mut Self` and returns `()`
   |
LL | ...
   |
help: you might have meant to use `values` after calling `sort`
  |
3 -     let sorted = values.sort();
4 -     println!("{}", sorted[0]);
3 +     values.sort();
4 +     println!("{}", values);
  |
Rationale and extra context

At the very least we should be pointing at the place where a binding was turned into ().

Other cases
We need to account for this in assignments, binops, unops, method calls and returns.
Rust Version
1.97
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

Start with the Rust reproducer and compare the current and desired diagnostics. Trace how the compiler reports a value inferred as () after assignments, binary and unary operations, method calls, and returns. Done means the diagnostic points to the binding that became () and provides the appropriate method-call context and suggestion for this case.

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
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.