rust - 返回对 Rc<RefCell<_>> 内容的引用时的生命周期

标签 rust lifetime

这个问题在这里已经有了答案:





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/

相关文章:

c++ - 临时延长生命周期

rust - 由于需求冲突,无法推断出 autoref 的适当生命周期

Rust 错误处理——捕获多个错误

rust - 为什么允许在 &mut self 中借用结构成员,但不允许借用 self 到不可变方法?

c++ - c/c++ 中局部变量的作用域和生命周期的困惑

recursion - 在 Rust 中返回一个递归闭包

pattern-matching - 在 Rust 中切换输入源的最佳方式

rust - ops traits 怎么可能不在范围内?

Rust:无法访问子目录中的函数

json - 读入json文件,写入不缩进