gpt4 book ai didi

rust - 从 Box 切换到 Rc 以获取类似 Scheme 的缺点列表不会编译

转载 作者:行者123 更新时间:2023-11-29 08:35:14 26 4
gpt4 key购买 nike

如果 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;

到程序的开头。

关于rust - 从 Box<T> 切换到 Rc<T> 以获取类似 Scheme 的缺点列表不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52486174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com