这个问题在这里已经有了答案:
How do I return a reference to something inside a RefCell without breaking encapsulation?
(3 个回答)
How do I borrow a RefCell<HashMap>, find a key, and return a reference to the result? [duplicate]
(1 个回答)
1年前关闭。
如何从共享指针(在本例中为 Rc<RefCell<_>>
)中返回对某些内容的引用?在下面的示例中,我展示了如何仅使用对 self
的常规可变引用来完成它。 ,但如果它改为共享指针,编译器会因为返回类型缺少生命周期说明符而生气。
error[E0106]: missing lifetime specifier
--> src/main.rs:19:60
|
19 | fn add_to_shared(me: Rc<RefCell<Thing>>, item: i32) -> &i32 {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
help: consider using the `'static` lifetime
|
19 | fn add_to_shared(me: Rc<RefCell<Thing>>, item: i32) -> &'static i32 {
| ^^^^^^^^
use std::cell::RefCell;
use std::rc::Rc;
struct Thing {
items: Vec<i32>,
}
impl Thing {
fn new() -> Self {
Thing { items: Vec::new() }
}
fn add_to_self(&mut self, item: i32) -> &i32 {
self.items.push(item);
self.items.last().unwrap()
}
// does not compile
fn add_to_shared(me: Rc<RefCell<Thing>>, item: i32) -> &i32 {
me.borrow().items.push(item);
me.borrow().items.last().unwrap()
}
}
fn main() {
let mut thing = Thing::new();
println!("{}", thing.add_to_self(10));
let mut rc = Rc::new(RefCell::new(Thing::new()));
println!("{}", rc.add_to_shared(20));
}
我为什么要这样做?我有一个程序可以构建具有多个所有权的树状结构。其中一个关联方法采用树的两个节点(每个节点共享指针)并将它们捆绑在一起到树的另一部分。每个方法都返回对新创建节点的引用,以便可以方便地注销它(参见示例)。我在想我需要使用生命周期注释来让它工作,但我无法找到如何将这个概念应用到
Rc<RefCell<_>>
的内部。类型。
最佳答案
我认为这里的问题是 Rust 知道多久 self
生活,但无法计算出多久 Rc<RefCell<_>>
存在。是否需要退货i32
引用?如果您只返回 i32
,该值将被复制,并且您不会引用可能不存在足够长的结构。
关于rust - 返回对 Rc<RefCell<_>> 内容的引用时的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64030274/