Skip to content

Diagnostic for E0596 points at the wrong borrow? #68786

Open
@lf-

Description

@lf-

I was writing the following function but forgot to put .as_mut_slice() rather than .as_slice():

fn find_closest(input: &str, options: &Vec<&str>) {
    let mut distances: Vec<_> = options
        .iter()
        .map(|_| ("a", 1.)) // actual code removed but types are the same
        .collect();
    distances
        .as_slice()
        .sort_unstable_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
}

This produced a E0596, with a message that I had trouble with as someone new to Rust:

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src\app.rs:18:5
   |
18 | /     distances
19 | |         .as_slice()
   | |___________________^ cannot borrow as mutable

error: aborting due to previous error

When trying to figure out what the compiler was taking issue with, I thought that it meant that it wanted the elements in the Vec to be themselves mutable, which didn't make any sense to me.

I think the diagnostic is referring to the borrow done by the .sort_unstable_by(F), but it is not pointing at it and the current message can be misread as meaning that the .as_slice() is borrowing something improperly itself, which it is not.

The diagnostic would be more helpful if it was something like this:

error[E0596]: cannot borrow data in a `&` reference as mutable
  --> src\app.rs:18:5
   |
18 | /     distances
19 | |         .as_slice()
20 | |         .sort_unstable_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
   | |_____________^ sort_unstable_by cannot borrow &self as mutable

error: aborting due to previous error
rustc --version
rustc 1.42.0-nightly (212b2c7da 2020-01-30)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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