0

I have the following code (dumbed down a bit from the code I had), that recursively traverses mutable list until certain condition is hit.

struct Node {
    value: usize,
    next: Option<Box<Node>>,
}
fn recursive<'a>(link: &'a mut Option<Box<Node>>) -> Option<&'a mut Option<Box<Node>>> {
    {
        match link.as_mut() {
            None => (),
            Some(cur) => {
                let next: &mut Option<Box<Node>> = &mut cur.next;
                return recursive(next);
            }
        }
    }
    return Some(link);
}

fn main() {
}

But the code doesn't compile with the following error message:

error[E0499]: cannot borrow `*link` as mutable more than once at a time
  --> <anon>:16:17
   |
7  |         match link.as_mut() {
   |               ---- first mutable borrow occurs here
...
16 |     return Some(link);
   |                 ^^^^ second mutable borrow occurs here
17 | }
   | - first borrow ends here

I thought this code would work because the first borrow @ the match line link.as_mut() would end as soon as the match is done, thus link can be borrowed again. Is that incorrect?

If I change the code to not use pattern matching but use link.as_mut().unwrap(), the code also compiles.

What is going on here?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jeeyoung Kim
  • 5,827
  • 8
  • 44
  • 54

0 Answers0