【发布时间】:2018-09-24 19:33:27
【问题描述】:
如果将Rc 替换为Box,则下面的程序将编译并运行。为什么使用引用计数时不编译?这是一个关于Rc<T>和Box<T>区别的问题。
use std::rc::Rc;
#[derive(Debug, Clone)]
pub enum ILst {
Nil,
Cons(i32, Rc<ILst>),
}
impl ILst {
pub fn new() -> Self {
ILst::Nil
}
pub fn cons(self, item: i32) -> Self {
ILst::Cons(item, Rc::new(self))
}
pub fn car(&self) -> Option<i32> {
match *self {
ILst::Cons(u, ref _v) => Some(u),
ILst::Nil => None,
}
}
pub fn cdr(&self) -> Self {
match *self {
ILst::Cons(_u, ref v) => *v.clone(),
ILst::Nil => ILst::Nil,
}
}
}
fn main() {
let list = ILst::new().cons(17).cons(29);
let rest = list.cdr();
println!("list = {:?}", rest);
}
error[E0507]: cannot move out of borrowed content
--> src/main.rs:27:38
|
27 | ILst::Cons(_u, ref v) => *v.clone(),
| ^^^^^^^^^^ cannot move out of borrowed content
【问题讨论】:
-
我相信How do I get an owned value out of a
Box?的答案已经回答了你的问题:“因为Box很特别”。如果您不同意,请edit您的问题解释差异。否则,我们可以将此问题标记为已回答。 -
Rc<T>和Box<T>之间的区别——是的,Boxis special。
标签: rust match refcounting