如何使用引用计数组织对Rust中同一对象的多个引用?
我有一个表示多项式的结构,我希望多个多项式引用同一个可变的如何使用引用计数组织对Rust中同一对象的多个引用?,rust,reference-counting,borrow-checker,Rust,Reference Counting,Borrow Checker,我有一个表示多项式的结构,我希望多个多项式引用同一个可变的别名对象。在JavaScript中,我会创建一个别名对象的实例,并将其分配给p1.别名,p2.别名等等。在Rust中,据我所知,我需要使用RefCell,它应该执行引用计数,因为Rust中没有垃圾收集器: extern crate rand; use std::collections::HashMap; use std::cell::RefCell; use std::collections::*; pub struct Aliase
别名
对象。在JavaScript中,我会创建一个别名
对象的实例,并将其分配给p1.别名
,p2.别名
等等。在Rust中,据我所知,我需要使用RefCell
,它应该执行引用计数,因为Rust中没有垃圾收集器:
extern crate rand;
use std::collections::HashMap;
use std::cell::RefCell;
use std::collections::*;
pub struct Aliases {
pub idx_to_name: HashMap<i16, String>,
pub name_to_idx: HashMap<String, i16>,
}
pub struct Polynome {
pub poly: BTreeMap<i16, f64>,
pub aliases: RefCell<Aliases>,
}
impl Aliases {
pub fn new() -> Aliases {
Aliases {
idx_to_name: HashMap::new(),
name_to_idx: HashMap::new(),
}
}
}
impl Polynome {
pub fn new() -> Polynome {
Polynome {
poly: BTreeMap::new(),
aliases: RefCell::new(Aliases::new()),
}
}
pub fn clone(&self) -> Polynome {
Polynome {
poly: self.poly.clone(),
aliases: self.aliases,
}
}
}
克隆多项式
的正确方法是什么,以便所有克隆引用相同的别名
实例
请注意,这个问题不是重复的。因为如果我尝试按照那里的建议,用生命周期声明来组织引用:
pub struct Polynome<'a> {
pub poly: BTreeMap<i16, f64>,
pub aliases: &'a RefCell<Aliases>
}
pub结构多项式{
让别名=RefCell::new(别名::new());
多项式{
poly:BTreeMap::new(),
别名:&别名,
}
}
错误[E0597]:`alias`的寿命不够长
|
24 |别名:&别名,
|^^^^^^^活得不够长
25 | }
26 | }
|-借来的价值仅在此处有效
|
注意:借用值必须在impl 19:1定义的生命周期“a”内有效。。。
如果我需要别名实例在::new()之外生存,我应该如何创建它?引用计数由
Rc
或Arc
完成,而不是RefCell
。您可以将RefCell
放入Rc
中,使其既可更改又可计算引用。@Shepmaster,请将其取消标记为重复,以便人们可以参与。它仍然是重复的,您需要的具体细节在注释中。因为这似乎很难找到,所以我把它移到了公认的答案中(这也是@interjay所说的-Rc
或Arc
)。
pub fn new() -> Polynome<'a> {
let alias= RefCell::new (Aliases::new());
Polynome {
poly: BTreeMap::new(),
aliases: &alias,
}
}
error[E0597]: `alias` does not live long enough
|
24 | aliases: &alias,
| ^^^^^ does not live long enough
25 | }
26 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on the impl at 19:1...