rust - 从 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
解决方案
解决方案似乎是更换
*v.clone()
和
Rc::deref(v).clone()
然后添加该行
use::ops::Deref;
到程序的开头。
推荐阅读
- mysql - Mysql:对多条记录应用条件
- c# - 如何使用c#滚动Winapp驱动程序中的下拉和列表框等区域?
- html - 如何更改引导 4 网格中的偏移大小?
- java - 检查 Java \$ 或 \ 中的一组特定元字符,
- maxmind - MaxMind Geolite2-City 不显示城市和地区信息
- ethereum - 为什么我所有的 Remix 测试账户都显示 0 ETH?
- python - 如何在python中将数据从分页API转换为pandas DataFrame
- javascript - ajax调用后替换类名
- google-cloud-platform - GCP:Vision API:获取认证错误
- shopify - Shopify,让用户直接从您的网站/应用程序登陆结帐页面