Skip to content

Add nuance to suggestion of !Copy expressions in for loops #82916

Open
@estebank

Description

@estebank

Given

struct S(i32);
fn foo(x: Vec<S>) {
    for y in x {
        
    }
    let z = x;
}

we currently suggest borrowing x:

error[E0382]: use of moved value: `x`
   --> src/lib.rs:6:13
    |
2   | fn foo(x: Vec<S>) {
    |        - move occurs because `x` has type `Vec<S>`, which does not implement the `Copy` trait
3   |     for y in x {
    |              -
    |              |
    |              `x` moved due to this implicit call to `.into_iter()`
    |              help: consider borrowing to avoid moving into the for loop: `&x`
...
6   |     let z = x;
    |             ^ value used here after move
    |
note: this function takes ownership of the receiver `self`, which moves `x`

The note doesn't have a span, so we should remove it when it is DUMMY_SP.

When we make the y pattern mut, we get the same output.

We should likely suggest .iter_mut() when the pattern is mutable, and the expression isn't Copy.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-iteratorsArea: IteratorsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`P-lowLow priorityT-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