Skip to content

E0502 diagnostic missing help text when using IndexMut instead of .get_mut. #95574

Closed
@BGR360

Description

@BGR360

Given the following code (playground):

fn main() {
    let mut vec = vec![0u32; 420];

    vec[vec.len() - 1] = 123;
}

The current output is:

error[E0502]: cannot borrow `vec` as immutable because it is also borrowed as mutable
 --> src/main.rs:4:9
  |
4 |     vec[vec.len() - 1] = 123;
  |     ----^^^^^^^^^-----
  |     |   |
  |     |   immutable borrow occurs here
  |     mutable borrow occurs here
  |     mutable borrow later used here

When you use .get_mut instead, you get a helpful hint advising you to extract the immutable borrow to a local variable (playground):

fn main() {
    let mut vec = vec![0u32; 420];

    *vec.get_mut(vec.len() - 1).unwrap() = 123;
}
error[E0502]: cannot borrow `vec` as immutable because it is also borrowed as mutable
 --> src/main.rs:4:18
  |
4 |     *vec.get_mut(vec.len() - 1).unwrap() = 123;
  |      ------------^^^^^^^^^-----
  |      |   |       |
  |      |   |       immutable borrow occurs here
  |      |   mutable borrow later used by call
  |      mutable borrow occurs here
  |
help: try adding a local storing this argument...
 --> src/main.rs:4:18
  |
4 |     *vec.get_mut(vec.len() - 1).unwrap() = 123;
  |                  ^^^^^^^^^
help: ...and then using that local as the argument to this call
 --> src/main.rs:4:6
  |
4 |     *vec.get_mut(vec.len() - 1).unwrap() = 123;
  |      ^^^^^^^^^^^^^^^^^^^^^^^^^^

Ideally the output for the first code snippet should contain the same help message.

@rustbot label +D-terse +D-confusing +D-newcomer-roadblock

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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