首页 > 解决方案 > 从 Box 切换到 Rc对于类似 Scheme 的 Cons 列表无法编译

问题描述

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

标签: rustmatchrefcounting

解决方案


解决方案似乎是更换

*v.clone()

Rc::deref(v).clone()

然后添加该行

use::ops::Deref;

到程序的开头。


推荐阅读