Description
Hello,
There is a case where the Rust compiler error message is misleading. I tried this code :
fn main() {
let mut values = vec![10, 11, 12];
let v = &mut values;
let mut max = 0;
for n in v {
max = std::cmp::max(max, *n);
}
println!("max is {}", max);
println!("Converting to percentages of maximum value...");
for n in v {
*n = 100 * (*n) / max;
}
println!("values: {:#?}", values);
}
…which gives the following error message, and misleading « help » message :
error[E0382]: use of moved value: `v`
--> src/main.rs:13:14
|
3 | let v = &mut values;
| - move occurs because `v` has type `&mut Vec<i32>`, which does not implement the `Copy` trait
...
7 | for n in v {
| -
| |
| `v` moved due to this implicit call to `.into_iter()`
| help: consider borrowing to avoid moving into the for loop: `&v`
...
13 | for n in v {
| ^ value used here after move
|
Especially, the help: consider borrowing to avoid moving into the for loop: '&v'
is the misleading part, does not help solve the problem at all, and sent me an a wrong path.
As I am new to Rust, this got me scratching my head for some time until someone explained it to me (here).
(And since the Rust compiler is most of the time very helpful, I did not even consider that its suggestion could be wrong haha. Hm.)
Instead of this, maybe a short message explaining how to reborrow the reference in this kind of situation would be more helpful and less misleading ?
Thank you.
Meta
rustc --version --verbose
:
rustc 1.48.0 (7eac88abb 2020-11-16)
binary: rustc
commit-hash: 7eac88abb2e57e752f3302f02be5f3ce3d7adfb4
commit-date: 2020-11-16
host: x86_64-unknown-linux-gnu
release: 1.48.0
LLVM version: 11.0