1

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');
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
rthota50
  • 15
  • 6
  • Actually, I believe that your entire problem will be solved if you read and understand http://stackoverflow.com/a/34279224/155423 and look at the signature for `unwrap`. – Shepmaster Jul 20 '16 at 02:46

1 Answers1

0

You need to borrow the content of the Option as mutable, see Option::as_mut() documentation.

head.left.as_mut().unwrap().add_left('A');

Here a playpen with a working version

rnstlr
  • 1,627
  • 14
  • 17