有人告诉我如何实现链表:
enum List {
Cons(u32, Box<List>),
Nil,
}
impl List {
fn prepend(self, elem: u32) -> List {
Cons(elem, Box::new(self))
}
}
当我想使用时prepend
,我需要执行以下操作:
list = list.prepend(1);
但是,我想创建一个不需要每次都创建新变量的函数prepend
返回。我只是想改变list
变量本身使用prepend
:
list.prepend(1);
这是我提出的一种实现,但它是不正确的:
fn my_prepend(&mut self, elem: u32) {
*self = Cons(elem, Box::new(*self));
}
错误是:
error[E0507]: cannot move out of borrowed content
List::prepend
must move self
因为这确实是正在发生的事情。列表的新头是一个新对象,旧头被移动到堆上,使旧变量无效。
Inside my_prepend
你有一个可变的引用self
,但随后你移动它的值,以便self
参考变得无效。虽然只是暂时无效,但是消息就是这样的"cannot move out of borrowed content"
正在抱怨。
解决这个问题的一种方法是移动self
输出到变量中并且同时地替换为Nil
, 所以这样self
引用永远不会无效。你可以这样做mem::replace
:
use std::mem;
fn my_prepend(&mut self, elem: u32) {
// Move the value of self into head, and leave self as Nil so it isn't invalid
let head = mem::replace(self, List::Nil);
// Reassign to self with the prepended value
*self = head.prepend(elem);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)