Question

I'm trying to write a recursive method that adds an item to a tree and returns the tree node corresponding to that item.

enum BstNode {
    Node(int, ~BstNode, ~BstNode),
    Leaf
}

impl BstNode {
    fn insert<'a>(&'a mut self, item: int) -> &'a mut BstNode {
        match *self {
            Leaf => {
                *self = Node(item, ~Leaf, ~Leaf);
                self
            },
            Node(ref node_item, ref mut left, ref mut right) =>
                match item.cmp(node_item) {
                    Less => left.insert(item),
                    Equal => self,
                    Greater => right.insert(item)
                }
        }
    }
}

I'm bitten by the following error:

bst.rs:19:30: 19:34 error: cannot move out of `self` because it is borrowed
bst.rs:19                     Equal => self,
                                       ^~~~
bst.rs:16:18: 16:31 note: borrow of `self#0` occurs here
bst.rs:16             Node(ref node_item, ref mut left, ref mut right) =>
                           ^~~~~~~~~~~~~

What does "moving out of something" mean? How do I fix this error?

I'm using Rust 0.10.

Was it helpful?

Solution

In your example node_item, left and right are owned by the self variable. The borrow checker doesn't know that in the Equal branch of

match item.cmp(node_item) {
    Less => left.insert(item),
    Equal => self,
    Greater => right.insert(item)
}

neither node_item, left nor right is used, but it sees that self is moving (you are returning it) while those 3 variables are still borrowed (you are still in the lexical scope of the match, where they are borrowed). I think this is a known bug that this behavior is too strict, see issue #6993.

As for the best way to fix the code, honestly I'm not sure. I would go with using a completely different structure (at least until the previous bug is fixed) :

pub struct BstNode {
  item: int,
  left: Option<~BstNode>,
  right: Option<~BstNode>
}

impl BstNode {
    pub fn insert<'a>(&'a mut self, item: int) -> &'a mut BstNode {
        match item.cmp(&self.item) {
            Less => match self.left {
              Some(ref mut lnode) => lnode.insert(item),
              None => {
                self.left = Some(~BstNode {item: item, left: None, right: None});
                &mut **self.left.as_mut().unwrap()
              }
            },
            Equal => self,
            Greater => match self.right {
              Some(ref mut rnode) => rnode.insert(item),
              None => {
                self.right = Some(~BstNode {item: item, left: None, right: None});
                &mut **self.right.as_mut().unwrap()
              }
            }
        }
    }
}

This way when you return your node, you never have any of its members still borrowed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top