I am trying to build a simple Node
struct with two pointers, the compiler complains that I have moved. I understand the error, but I don't see how to get around the issue.
#[derive(Debug)]
struct Node {
val: char,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn new(c: char) -> Box<Node> {
let new_node = Node {
val: c,
left: None,
right: None,
};
println!("new Node {}", c);
return Box::new(new_node);
}
pub fn add_left(&mut self, c: char) {
let n_node = Node::new(c);
let target = &mut self.left;
*target = Some(n_node);
}
pub fn add_right(&mut self, c: char) {
let n_node = Node::new(c);
let target = &mut self.right;
*target = Some(n_node);
}
}
fn main() {
println!("Hello, world!");
let mut head = Node::new('M');
head.add_left('C');
head.left.unwrap().add_left('A');
head.add_right('N');
}
Throws the following
error: use of partially moved value: `*head` [E0382]
head.add_right('N');
^~~~
help: run `rustc --explain E0382` to see a detailed explanation
note: `head.left` moved here because it has type `std::option::Option<Box<Node>>`, which is non-copyable
head.left.unwrap() .add_left('A');