I'm working on a Rust implementation of a binary search tree. I'm getting an error by calling one of the node's functions after printing the node's values:
#[derive(Default)]
//# [derive(Copy)]
pub struct Node {
data: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
//option is used when the property could either be a type or None.
//if just `left: Node`, rust will panic because `recursive without indirection`
//impl Copy for Node { }
// impl Clone for Node {
// fn clone(&self) -> Node {
// *self
// }
// }
impl Node {
fn print_data(&self) -> i32 {
self.data
}
fn default() -> Node {
//function to help when instantiate node with no children
Node {
data: 0,
left: None,
right: None,
}
}
fn set_left(&mut self, new_left: Option<Box<Node>>) -> () {
self.left = new_left
}
fn set_right(&mut self, new_right: Option<Box<Node>>) -> () {
self.right = new_right
}
fn swap_childs(&mut self) -> () {
std::mem::swap(&mut self.left, &mut self.right);
}
}
fn get_data(a_node: &Node) -> i32 {
a_node.data
}
fn main() {
let node4 = Node {
data: 4,
..Default::default()
};
let mut node3 = Node {
data: -3,
..Default::default()
};
node3.set_left(Some(Box::new(node4)));
let node5 = Node {
data: 5,
..Default::default()
};
node3.set_right(Some(Box::new(node5)));
// We have a tree!?
println!("node3 val is {}", get_data(&node3));
let left = get_data(&node3.left.unwrap());
println!("node3 left val is {}", left);
let right = get_data(&node3.right.unwrap());
println!("node3 right val is {}", right);
node3.swap_childs(); //causes error
}
Here's my error
error[E0382]: borrow of moved value: `node3`
--> src/main.rs:76:5
|
73 | let right = get_data(&node3.right.unwrap());
| ----------- value moved here
...
76 | node3.swap_childs(); //causes error
| ^^^^^ value borrowed here after partial move
|
= note: move occurs because `node3.right` has type `std::option::Option<std::boxed::Box<Node>>`, which does not implement the `Copy` trait
I'm aware that the reason for this error is because my struct can't implement the Copy
trait (because of Box
?) (see commented out Copy
and Clone
implementation). I thought the get_data
function / mut
declaration would help. How can I solve this?