Skip to content

Use of moved value error in the for iterator could give a hint about borrowing #25534

Closed
@lifthrasiir

Description

@lifthrasiir
fn main() {
    let a = vec![1, 2, 3];
    for i in a {
        for j in a {
            println!("{} * {} = {}", i, j, i * j);
        }
    }
}

currently gives:

<anon>:4:18: 4:19 error: use of moved value: `a`
<anon>:4         for j in a {
                          ^
note: in expansion of for loop expansion
<anon>:4:9: 6:10 note: expansion site
note: in expansion of for loop expansion
<anon>:3:5: 7:6 note: expansion site
<anon>:3:14: 3:15 note: `a` moved here because it has type `collections::vec::Vec<i32>`, which is non-copyable
<anon>:3     for i in a {
                      ^
note: in expansion of for loop expansion
<anon>:3:5: 7:6 note: expansion site
error: aborting due to previous error

Of course, we all know that for i in &a etc. is correct here, but this is not very obvious to beginners. We may want to give a contextual hint for "use of moved value" errors among others---probably as a second note following the original move.

(Feel free to make this a metabug if there are other such examples.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-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.WG-diagnosticsWorking group: Diagnostics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions