Skip to content

Unhelpful / misleading error message and help message when using a reference to a vector #83924

Open
@njor

Description

@njor

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-coercionsArea: implicit and explicit `expr as Type` coercionsA-iteratorsArea: IteratorsC-bugCategory: This is a bug.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