Your insertleft
and insertright
functions take self
, which tranfers ownership of the BinaryTree
to those functions. They then return it, which you currently discard.
If you want to construct the tree step by step, you can store those return values in new variables to be re-used:
let tree = BinaryTree::new(1);
let tree = tree.insertleft(BinaryTree::new(2));
let tree = tree.insertright(BinaryTree::new(3));
Alternatively, if you don't need to chain construction and insertions, you can take &mut
reference to self
:
impl<T: std::clone::Clone> BinaryTree<T> {
pub fn insertleft(&mut self, node: BinaryTree<T>) {
let left_option = Some(Box::new(node));
self.left = left_option;
}
pub fn insertright(&mut self, node: BinaryTree<T>) {
let right_option = Some(Box::new(node));
self.right = right_option;
}
}
fn main() {
let mut tree = BinaryTree::new(1);
tree.insertleft(BinaryTree::new(2));
tree.insertright(BinaryTree::new(3));
}
This reference allows insertleft
and insertright
to modify tree
in place, keeping ownership of the BinaryTree
in main
. However, you can no longer chain construction and insertion because BinaryTree::new(1).insertleft(BinaryTree::new(2)).insertright(BinaryTree::new(3))
would yield a reference to a temporary value.
For more information, see https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html and Is there a difference between using a reference, and using an owned value in Rust?