Skip to content

Borrow checker bug with double borrow #108704

@MatiasLyyra

Description

@MatiasLyyra

Hi,

I came across following weird borrow check behaviour.
If you uncomment elements = &mut elements[idx].children; and comment line below, program compiles ok. I think this is a bug.

I tried this code:

struct Root {
    children: Vec<Node>,
}

struct Node {
    name: String,
    children: Vec<Node>,
}

fn merge_tree(root: &mut Root, path: Vec<String>) {
    let mut elements = &mut root.children;

    for p in path.iter() {
        for (idx, el) in elements.iter_mut().enumerate() {
            if el.name == *p {
                // elements = &mut elements[idx].children;
                elements = &mut el.children;
                break;
            }
        }
    }
}

I expected to see this happen: No compiler error.

Instead, this happened: Following compiler error:

error[E0499]: cannot borrow `*elements` as mutable more than once at a time
  --> src/main.rs:29:26
   |
29 |         for (idx, el) in elements.iter_mut().enumerate() {
   |                          ^^^^^^^^^^^^^^^^^^^
   |                          |
   |                          `*elements` was mutably borrowed here in the previous iteration of the loop
   |                          first borrow used here, in later iteration of loop

Meta

rustc --version --verbose:

rustc 1.67.1 (d5a82bbd2 2023-02-07)
binary: rustc
commit-hash: d5a82bbd26e1ad8b7401f6a718a9c57c96905483
commit-date: 2023-02-07
host: aarch64-apple-darwin
release: 1.67.1
LLVM version: 15.0.6
Backtrace

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-poloniusCompiling with `-Zpolonius` fixes this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions