title: Rust: Implement AVL Tree and error: thread 'main' panicked at 'already borrowed: BorrowMutError'
body: <p>I have the following tree structure:</p>
  <pre><code>use std::cell::RefCell;
  use std::rc::Rc;
  use std::cmp;
  use std::cmp::Ordering;
  
  type AVLTree&lt;T&gt; = Option&lt;Rc&lt;RefCell&lt;TreeNode&lt;T&gt;&gt;&gt;&gt;;
  
  #[derive(Debug, PartialEq, Clone)]
  struct TreeSet&lt;T: Ord&gt; {
      root: AVLTree&lt;T&gt;,
  }
  
  impl&lt;T: Ord&gt; TreeSet&lt;T&gt; {
      fn new() -&gt; Self {
          Self { 
              root: None 
          }
      }
  
      fn insert(&amp;mut self, value: T) -&gt; bool {
          let current_tree = &amp;mut self.root;
  
          while let Some(current_node) = current_tree {
  
              let node_key = &amp;current_node.borrow().key;
            
              match node_key.cmp(&amp;value) {
                  Ordering::Less =&gt; { let current_tree = &amp;mut current_node.borrow_mut().right; },
                  Ordering::Equal =&gt; {
                      return false;
                  }
                  Ordering::Greater =&gt; { let current_tree = &amp;mut current_node.borrow_mut().left; },
              }
          }
  
          *current_tree = Some(Rc::new(RefCell::new(TreeNode {
              key: value,
              left: None,
              right: None,
              parent: None
          })));
  
          true
      }
  
  }
  
  
  #[derive(Clone, Debug, PartialEq)]
  struct TreeNode&lt;T: Ord&gt; {
      pub key: T,
      pub parent: AVLTree&lt;T&gt;,
      left: AVLTree&lt;T&gt;,
      right: AVLTree&lt;T&gt;,
  }
  
  
  fn main() {
      let mut new_avl_tree: TreeSet&lt;u32&gt; = TreeSet::new();
      new_avl_tree.insert(3);
      new_avl_tree.insert(5);
      println!(&quot;Tree: {:#?}&quot;, &amp;new_avl_tree);
  }
  </code></pre>
  <p>Building with <code>cargo build</code> is fine, but when I run <code>cargo run</code>, I got the below error:</p>
  <blockquote>
  <p>thread 'main' panicked at 'already borrowed: BorrowMutError', src\libcore\result.rs:1165:5</p>
  <p>note: run with <code>RUST_BACKTRACE=1</code> environment variable to display a backtrace. error: process didn't</p>
  <p>exit successfully: <code>target\debug\avl-tree.exe</code> (exit code: 101)</p>
  </blockquote>
  <p>If i just call <code>insert(3)</code>, it will be fine and my tree gets printed correctly. However, if I <code>insert(5)</code> after <code>insert(3)</code>, I will get that error.</p>
  <p>How do I fix that?</p>