1

I was trying to implement a binary tree, and I'm stuck with implementing an insert operation:

use std::cmp::PartialOrd;

type Link<T> = Option<Box<Node<T>>>;

struct Node<T: PartialOrd> {
    val: T,
    left: Link<T>,
    right: Link<T>,
}

struct Tree<T: PartialOrd> {
    root: Link<T>,
}

impl<T: PartialOrd> Tree<T> {
    fn new() -> Self {
        Tree { root: None }
    }

    fn add(&mut self, val: T) {
        let mut prev: Option<&mut Node<T>> = None;
        let mut cur = self.root.as_mut();

        while let Some(boxed_node_ref) = cur {
            if val < boxed_node_ref.val {
                cur = boxed_node_ref.left.as_mut();
            } else {
                cur = boxed_node_ref.right.as_mut();
            }
            prev = Some(boxed_node_ref);
        }
    }
}

fn main() {
    println!("It's ok...");
}

The error is:

error[E0499]: cannot borrow `**boxed_node_ref` as mutable more than once at a time
  --> src/main.rs:30:25
   |
24 |         while let Some(boxed_node_ref) = cur {
   |                                            - first borrow ends here
25 |             if val < boxed_node_ref.val {
26 |                 cur = boxed_node_ref.left.as_mut();
   |                       ------------------- first mutable borrow occurs here
...
30 |             prev = Some(boxed_node_ref);
   |                         ^^^^^^^^^^^^^^ second mutable borrow occurs here

I don't understand why it tells me that I'm borrowing boxed_node_ref second time. I suppose that I'm moving it.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I believe your question is answered by the answers of [Cannot obtain a mutable reference when iterating a recursive structure: cannot borrow as mutable more than once at a time](https://stackoverflow.com/q/37986640/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jul 30 '18 at 19:47
  • 1
    [The duplicate applied to your question](https://play.rust-lang.org/?gist=da1abad240a5d1f8e16e914be2ddde57&version=stable&mode=debug&edition=2015). – Shepmaster Jul 30 '18 at 19:47
  • 1
    See also [Is there a way to iterate over a mutable tree to get a random node?](https://stackoverflow.com/q/49057270/155423) for why you **cannot** keep a previous reference. – Shepmaster Jul 30 '18 at 19:52

0 Answers0