Newtang
Newtang

Reputation: 6544

Cannot assign to variable because it is borrowed

I'm trying to re-assign a variable in a loop, but I keep running into cannot assign to `cur_node` because it is borrowed. Below I commented out the loop for simplicity, and it's the same problem. How do I handle this?

fn naive_largest_path(root: Rc<RefCell<Node>>) {
    let mut cur_node = root.clone();
    let cur_node_borrowed = cur_node.borrow();

    // while cur_node_borrowed.has_children() {
        let lc = cur_node_borrowed.left_child.as_ref().unwrap();

        let left_child = cur_node_borrowed.left_child.as_ref().unwrap();
        let right_child = cur_node_borrowed.right_child.as_ref().unwrap();

        let left_val = left_child.borrow().value;
        let right_val = right_child.borrow().value;

        if left_val > right_val {
            cur_node = left_child.clone();
        } else {
            cur_node = right_child.clone();
        }
    // }
}

struct Node {
    value: i32,
    row_num: i32,
    position_in_row: i32,
    left_child: Option<Rc<RefCell<Node>>>,
    right_child: Option<Rc<RefCell<Node>>>,
}

impl Node {
    fn new(val: i32, row: i32, pos_in_row: i32) -> Rc<RefCell<Node>> {
        Rc::new(RefCell::new(Node {
            value: val,
            row_num: row,
            position_in_row: pos_in_row,
            left_child: None,
            right_child: None,
        }))
    }

    fn has_children(&self) -> bool {
        self.left_child.is_some() || self.right_child.is_some()
    }
}

Upvotes: 14

Views: 8706

Answers (1)

Chris Emerson
Chris Emerson

Reputation: 14021

As the comments have said, you will need to restructure the code to make sure there is no borrow at the point where you want to assign to cur_node. When dealing with Rc you can also often get away with a few extra .clone(), but that's cheating (and a little less efficient) :-).

Here's one way that compiles, taking advantage of Rust's blocks-are-expressions feature:

fn naive_largest_path(root: Rc<RefCell<Node>>) {

    let mut cur_node = root.clone();

    while cur_node.borrow().has_children() {
        cur_node = {
            let cur_node_borrowed = cur_node.borrow();

            let lc = cur_node_borrowed.left_child.as_ref().unwrap();

            let left_child = cur_node_borrowed.left_child.as_ref().unwrap();
            let right_child = cur_node_borrowed.right_child.as_ref().unwrap();



            let left_val = left_child.borrow().value;
            let right_val = right_child.borrow().value;


            if left_val > right_val {
                left_child.clone()
            } else {
                right_child.clone()
            }
        };
    }
}

Upvotes: 11

Related Questions