Skip to content

Confusing lifetime error in the presence of a loop #81673

Open
@jyn514

Description

@jyn514

I just got the following error (playground):

error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
 --> src/main.rs:7:9
  |
3 |     let slice = v.as_slice();
  |                 - immutable borrow occurs here
...
6 |         f(slice);
  |           ----- immutable borrow later used here
7 |         v.push(2);
  |         ^^^^^^^^^ mutable borrow occurs here

The error alone does not give you enough info to see what's going wrong: push is called after f(slice), why is the borrow still active? You need to look at the whole code to realize it's because f is called in the next loop iteration:

    for _ in 0..5 {
        f(slice);
        v.push(2);
    }

It would be nice to include this info in the error - I think there are already some errors that say "borrowed in the next loop iteration".

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-control-flowArea: Control flowA-diagnosticsArea: Messages for errors, warnings, and lintsD-papercutDiagnostics: An error or lint that needs small tweaks.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