Move out of borrowed content issue


I am trying to write a B+Tree in Rust, but I’m running into a problem that seems like it should be simple to solve, but I’m at a bit of a loss. My issue arises when the root node of the tree is split; when this happens, a new root is created, and the old root is inserted as a child of the new root. Unfortunately, Rust is unhappy because that would involve moving “self.root” into new_root.children, leaving self.root uninitialized for a moment, even though on the very next line is “self.root = new_root”.

The relevant code…
pub fn insert(&mut self, key: K, value: V) {
if let Some(retval) = self.root.insert(key, value) {
let (pivot, new_node) = retval
let mut root: Box<InteriorNode<K, V>> = Box::new(InteriorNode::new());



In reading about ways around this, I’ve come across Rc, RefCell, mem::replace, etc. Before I venture off in a certain direction, I wanted to see if someone would have a suggestion as to what the best or canonical way to do this is.


I don’t know if it’s the “canonical” way to solve it, but I have seen mem::replace being used for this in @Gankro’s Learning Rust With Entirely Too Many Linked Lists.


That’s good reading, thanks.