使用部分移动的值:`* head`

时间:2016-07-20 02:27:48

标签: rust

我正在尝试使用两个指针构建一个简单的#[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'); } 结构,编译器抱怨我已经移动了。我理解错误,但我不知道如何解决这个问题。

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');

抛出以下内容

        var defaultImage = "/images/default_user.jpg";
        $.ajax({
            url: '/path/to/image.img',
            failure: function () {  
                 alert('Image not found in server');            
            },
            success: function () {
                defaultImage = "/path/to/image.img";
            }
        });

1 个答案:

答案 0 :(得分:1)

您需要将Option的内容借用为可变内容,请参阅Option::as_mut() documentation

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

此处playpen具有工作版