2014-08-30 71 views
4

了,我实现了一个简单的链表正是如此无法移动的&MUT指针

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来获取我想要的生命周期的版本,但这只是产生了额外的错误,而真正的问题似乎是我只是不愿意不明白为什么第一个版本不起作用。有人可以解释我做错了什么,并且/或者将我链接到可以解释这个问题的Rust文档?

回答

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 */ }