Open
Description
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)