这个问题在这里已有答案:
我有一个表示多项式的结构,我想要多个多项式来引用相同的 mutable Aliases
对象 . 在JavaScript中,我将创建 Aliases
对象的实例并将其分配给 p1.aliases
, p2.aliases
等等 . 在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,
}
}
}
但是我在 clone()
中遇到了编译错误:
error[E0507]: cannot move out of borrowed content
--> src/main.rs:36:22
|
36 | aliases: self.aliases,
| ^^^^ cannot move out of borrowed content
克隆 Polynome
的正确方法是什么,以便所有克隆引用相同的 Aliases
实例?
请注意,此问题与How to represent shared mutable state?不重复 . 因为如果我尝试组织带有生命周期声明的引用,那么:
pub struct Polynome<'a> {
pub poly: BTreeMap<i16, f64>,
pub aliases: &'a RefCell<Aliases>
}
然后我得到“活得不够长”的问题,而不是“不能搬出去”:
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...
如果我需要它在外面生活:: new(),我应该如何创建别名实例?