无法移动 &mut 指针。

4
我已经实现了一个简单的链表结构,如下所示:
struct List {

    data : String,
    cons : Option<Box<List>>
}

我有另一个结构体,其中有一个以下类型的成员变量,在下方定义:
pub struct Context {

    head : Option<Box<List>>
}

在这个结构体的一个函数run中,我有这段代码
let mut temp_head = &mut self.head;
let mut full_msg = "".to_string();
while temp_head.is_some() {
       let temp_node = temp_head.unwrap();
       full_msg.push_str(temp_node.data.as_slice());
       temp_head = temp_node.cons;
}

迭代链表并组装它们数据的字符串。然而,设置temp_node值的那行代码产生以下错误:cannot move out of dereference of &mut-pointer,编译器也抱怨我试图放入temp_head末尾的值在该块之后不存在。
我尝试在第一行克隆temp_head或在最后一行使用temp_node.cons来获得我想要的生命周期版本,但这只会产生其他错误,真正的问题似乎是我不明白为什么第一个版本不起作用。有人能解释一下我做错了什么,并/或者链接我到解释这个问题的Rust文档吗?
1个回答

4
你需要非常小心代码中的引用,问题是当使用unwrap()时,你确实尝试将temp_head的内容移出其容器。这个被移动的内容将在while块结束时被销毁,留下temp_head引用已删除的内容。
你需要一直使用引用,而对于这种情况,使用模式匹配比使用unwrap()is_some()更为适当,像这样:
let mut temp_head = &self.head;
let mut full_msg = "".to_string();
while match temp_head {
    &Some(ref temp_node) => { // get a reference to the content of node
        full_msg.push_str(temp_node.data.as_slice()); // copy string content
        temp_head = &temp_node.cons; // update reference
        true // continue looping
    },
    &None => false // we reached the end, stop looping
} { /* body of while, nothing to do */ }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接