首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能移出&mut指针

不能移出&mut指针
EN

Stack Overflow用户
提问于 2014-08-30 23:36:44
回答 1查看 1.2K关注 0票数 4

我已经将一个简单的链表实现为一个结构化的列表

代码语言:javascript
复制
struct List {

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

我有另一个具有此类型成员的结构,定义如下

代码语言:javascript
复制
pub struct Context {

    head : Option<Box<List>>
}

在这个结构的函数中,运行,我有以下代码

代码语言:javascript
复制
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以获得我想要的版本,但是这只会产生额外的错误,而真正的问题似乎是我不明白为什么第一个版本不能工作。有人能解释我做错了什么,或者把我和解释这件事的锈菌文档联系起来吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-30 23:54:16

您需要非常小心地处理代码中的引用,问题是当使用temp_head时,首先确实尝试将unwrap()的内容从容器中移出。正在移动的该内容将在while块的末尾被销毁,留下temp_head引用已删除的内容。

您需要一路使用引用,对于此模式匹配比使用unwrap()is_some()更合适,如下所示:

代码语言:javascript
复制
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 */ }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25587655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档