tlent
tlent

Reputation: 94

Cannot borrow as mutable more than once error in a loop

I am working on leetcode problem #83 "Remove Duplicates from Sorted List", but I'm stuck on this borrow checker issue.

The ListNode struct is given by the problem so it cannot be changed. I have tried restructuring the loop and if statement, but I haven't found a working solution.

What I am trying to do:

// Definition for singly-linked list.
#[derive(PartialEq, Eq, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode { next: None, val }
    }
}

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = &mut list;
    while let Some(c) = cursor.as_mut() {
        if let Some(next) = c.next.as_mut() {
            if next.val == c.val {
                c.next = next.next.take();
                continue;
            }
        }
        cursor = &mut c.next;
    }
    list
}

The error I'm getting:

error[E0499]: cannot borrow `*cursor` as mutable more than once at a time
  --> src/lib.rs:17:25
   |
17 |     while let Some(c) = cursor.as_mut() {
   |                         ^^^^^^ mutable borrow starts here in previous iteration of loop

Simplified code that seems to show the same error:

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = &mut list;
    while let Some(c) = cursor.as_mut() {
        if c.val > 0 {
            cursor = &mut c.next;
        }
    }
    list
}

I don't understand why the mutable borrow hasn't been dropped before the next iteration of the loop. It seems to be caused by conditionally changing the cursor, but I don't see why that would prevent the borrow from being dropped.

Upvotes: 2

Views: 1100

Answers (1)

tlent
tlent

Reputation: 94

Here's the solution I ended up with. Reassigning cursor in the if statement fixes the problem.

fn remove_duplicates(mut list: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut cursor = list.as_mut();
    while let Some(c) = cursor {
        if let Some(next) = c.next.as_mut() {
            if next.val == c.val {
                c.next = next.next.take();
                cursor = Some(c);
                continue;
            }
        }
        cursor = c.next.as_mut();
    }
    list
}

Upvotes: 1

Related Questions