Lucas Lange
Lucas Lange

Reputation: 41

Why does the borrow checker seem to keep a reference borrowed in a match statement even after the end of the block?

Here is some code that causes my issue as succinctly as possible:

struct Parent {
    child: Option<Box<Parent>>,
}

fn main() {
    let mut parent = &mut Parent { child: None };

    match &mut parent.child { // error says parent.child is borrowed here...
        Some(inner) => {
            parent = inner;
        }
        None => (),
    }

    parent.child = None; // says cannot assign because parent.child is borrrowed
}

I would like to understand why the match statement does not allow me to use parent.child afterward and what I should do instead to achieve the effect of assigning parent to its child if that child exists?

Since this was an issue I faced while trying out making a BST, I found a correct implementation online of the function I wanted. However, I would still like to better understand why this does not pass so that I won't make the same mistake twice.

Upvotes: 4

Views: 61

Answers (0)

Related Questions