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.