Already borrowed error?

I have a Tree structure defined with the following data structures.
the root nodes are stored into a Vector.

pub struct Node {
    pub object: BmosHaystackObject,
    pub parent: Option<NodeRefNodeRefWeak>,
    pub children: Vec<NodeRef>,

pub type NodeRef = Rc<RefCell<Node>>;
pub type NodeRefNodeRefWeak = Weak<RefCell<Node>>;

root nodes: Vec<NodeRef>

I can build a tree using this structure and print out to json but I am having trouble doing some basic tree operations for example removing a node and its children.

I have the following method

fn tree_remove_node_children(node: &mut NodeRef) {

        let mut borrow = node.borrow_mut();
        let node_id: String =;
        for n in borrow.children.iter_mut() {


        let parent = node.borrow().parent.clone().expect("expected parent");

        let mut p = parent.upgrade().expect("expected upgrade");

        let mut children = &mut p.borrow_mut().children;

        children.retain(|n| n.borrow() != node_id );

Here I get panicked at 'already borrowed: BorrowMutError'
at the line

let mut children = &mut p.borrow_mut().children;

I am not sure how it is borrowed at this point ?
It there a better way to handle this ?

Note I have not tested whther the function would work as intended as I can't get past the borrow error at the moment.


Hmm on a first inspection, following along the code, inside of the for loop, you’ll have node being
borrowed from the borrow_mut(). Then there’s a recursive call to tree_remove_node_children(n) for the first child n. Inside of this recursive call, once the second half, let parent = node.borrow()... etc, is reached, the child will borrow itself borrow, access its parent and borrow the patent with borrow_mut().

The problem: The parent is already borrowed up the stack in the outer tree_remove_node_children.

So IMO it makes a lot of sense that you get this error message. Btw, just one node with a single child (and no grandchildren) is going to be enough to trigger this behavior.