Skip to content

MIR borrowck doesn't accept the example of iterating and updating a mutable reference #46589

Closed
@nikomatsakis

Description

@nikomatsakis

I expected this example from the NLL RFC to pass the MIR borrow checker:

struct List<T> {
    value: T,
    next: Option<Box<List<T>>>,
}

fn to_refs<T>(mut list: &mut List<T>) -> Vec<&mut T> {
    let mut result = vec![];
    loop {
        result.push(&mut list.value);
        if let Some(n) = list.next.as_mut() {
            list = n;
        } else {
            return result;
        }
    }
}

fn main() {
}

The idea here is that assigning to list is supposed to clear the existing borrows of list.{value,next}. However, it still gets errors for me:

lunch-box. rustc --stage1 iterate-mut-ref.rs  -Zborrowck=mir
error[E0499]: cannot borrow `list.value` as mutable more than once at a time
  --> iterate-mut-ref.rs:9:21
   |
9  |         result.push(&mut list.value);
   |                     ^^^^^^^^^^^^^^^ mutable borrow starts here in previous iteration of loop
...
16 | }
   | - mutable borrow ends here

error[E0499]: cannot borrow `list.next` as mutable more than once at a time
  --> iterate-mut-ref.rs:10:26
   |
10 |         if let Some(n) = list.next.as_mut() {
   |                          ^^^^^^^^^ mutable borrow starts here in previous iteration of loop
...
16 | }
   | - mutable borrow ends here

error[E0506]: cannot assign to `list` because it is borrowed
  --> iterate-mut-ref.rs:11:13
   |
9  |         result.push(&mut list.value);
   |                     --------------- borrow of `list` occurs here
10 |         if let Some(n) = list.next.as_mut() {
11 |             list = n;
   |             ^^^^^^^^ assignment to borrowed `list` occurs here

error: aborting due to 3 previous errors

cc @pnkfelix @arielb1

Metadata

Metadata

Assignees

Labels

A-MIRArea: Mid-level IR (MIR) - https://blog.rust-lang.org/2016/04/19/MIR.htmlA-NLLArea: Non-lexical lifetimes (NLL)A-diagnosticsArea: Messages for errors, warnings, and lintsC-bugCategory: This is a bug.I-ICEIssue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️NLL-completeWorking towards the "valid code works" goalP-mediumMedium 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