返回对Rc <RefCell <_ >>内容的引用时的生存期

问题描述

如何从共享指针(在本例中为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<_>>类型的内部。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)