我已经将一个简单的链表实现为一个结构化的列表
struct List {
data : String,
cons : Option<Box<List>>
}我有另一个具有此类型成员的结构,定义如下
pub struct Context {
head : Option<Box<List>>
}在这个结构的函数中,运行,我有以下代码
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以获得我想要的版本,但是这只会产生额外的错误,而真正的问题似乎是我不明白为什么第一个版本不能工作。有人能解释我做错了什么,或者把我和解释这件事的锈菌文档联系起来吗?
发布于 2014-08-30 23:54:16
您需要非常小心地处理代码中的引用,问题是当使用temp_head时,首先确实尝试将unwrap()的内容从容器中移出。正在移动的该内容将在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 */ }https://stackoverflow.com/questions/25587655
复制相似问题