Skip to content

E0596 should suggest changing type if it suggest taking taking mutable reference instead of just reference #106857

Open
@matthiaskrgr

Description

@matthiaskrgr

Given the following code:

fn main() {
    let x: &[isize] = &[1, 2, 3, 4, 5];
    // Can't mutably slice an immutable slice
    let _slice: &mut [isize] = &mut [0, 1];
    let _ = &mut x[2..4]; //~ERROR cannot borrow `*x` as mutable, as it is behind a `&` reference
}

The current output is:

error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference
 --> src/lib.rs:5:18
  |
5 |     let _ = &mut x[2..4]; //~ERROR cannot borrow `*x` as mutable, as it is behind a `&` reference
  |                  ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable
  |
help: consider changing this to be a mutable reference
  |
2 |     let x: &[isize] = &mut [1, 2, 3, 4, 5];
  |                       ~~~~~~~~~~~~~~~~~~~~

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

If we apply the suggestion this will cause the next problem, because &mut[1,2...] is not &[isize] but &mut [isize] 🙃

fn main() {
    let x: &[isize] = &mut [1, 2, 3, 4, 5];
    // Can't mutably slice an immutable slice
    let _slice: &mut [isize] = &mut [0, 1];
    let _ = &mut x[2..4]; //~ERROR cannot borrow `*x` as mutable, as it is behind a `&` reference
}

so we should suggest let x: &mut [isize] = &mut [1, 2, 3, 4, 5]; right away, if possible.

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsS-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-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