Skip to content

Explain iterator invalidation on borrow error when trying to modify currently looping vec #159489

Description

@estebank

Code

fn main() {
    let mut values = vec![1, 2, 3];

    // The diagnostic identifies the conflicting borrows, but does not explain
    // that the loop keeps `values` borrowed for the iteration or give any
    // beginner-facing guidance about restructuring the operation.
    for value in &values {
        if *value == 2 {
            values.push(4);
            //~^ ERROR cannot borrow `values` as mutable because it is also borrowed as immutable
        }
    }
}

Current output

error[E0502]: cannot borrow `values` as mutable because it is also borrowed as immutable
  --> $DIR/mutate-vec-while-iterating.rs:12:13
   |
LL |     for value in &values {
   |                  -------
   |                  |
   |                  immutable borrow occurs here
   |                  immutable borrow later used here
LL |         if *value == 2 {
LL |             values.push(4);
   |             ^^^^^^^^^^^^^^ mutable borrow occurs here

Desired output

It should explain iterator invalidation and render in a more pedagogical way.

Rationale and extra context

No response

Other cases

Rust Version

1.97

Anything else?

No response

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-papercutDiagnostics: An error or lint that needs small tweaks.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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