什么是“匿名生命周期#1”并且我如何正确地定义它?

7
我希望下面的Handler能够将自己推入列表中。
use std::vec::Vec;
use std::rc::Rc;
use std::cell::RefCell;

struct Handler<'a> {
    list: Rc<RefCell<Vec<&'a mut Handler<'a>>>>
}

impl<'a> Handler<'a> {
    fn new(list: Rc<RefCell<Vec<&'a mut Handler<'a>>>>) -> Self {
        Handler { list: list }
    }

    fn push(&mut self) {
        self.list.borrow_mut().push(self)
    }
}

fn main() {
    let list = Rc::new(RefCell::new(Vec::new()));

    let mut h1 = Handler::new(list);
    let mut h2 = Handler::new(list);

    h1.push();
    h2.push();

    // Here the list should contain both h1 and h2

}

但我遇到了这个错误,而且我找不到解决方法!

error[E0312]: lifetime of reference outlives lifetime of borrowed content...
  --> src/main.rs:15:37
   |
15 |         self.list.borrow_mut().push(self)
   |                                     ^^^^
   |
note: ...the reference is valid for the lifetime 'a as defined on the impl at 9:1...
  --> src/main.rs:9:1
   |
9  | / impl<'a> Handler<'a> {
10 | |     fn new(list: Rc<RefCell<Vec<&'a mut Handler<'a>>>>) -> Self {
11 | |         Handler { list: list }
12 | |     }
...  |
16 | |     }
17 | | }
   | |_^
note: ...but the borrowed content is only valid for the anonymous lifetime #1 defined on the method body at 14:5
  --> src/main.rs:14:5
   |
14 | /     fn push(&mut self) {
15 | |         self.list.borrow_mut().push(self)
16 | |     }
   | |_____^

“匿名生命周期 #1”是什么,我应该如何正确定义它?甚至,我的 Rust 代码是否正确解决了这个问题?

1个回答

8

“匿名生命周期#1”是什么?

“匿名”意味着没有名称的东西。生命周期是与引用相关联的事物。第14行上的引用在哪里?

fn push(&mut self)
//      ^ here

由于生命周期省略,您不需要明确指定生命周期,使其可以是隐式的(匿名的)。
您的代码要求Vec包含&'a mut Handler<'a>,但您正在尝试放入&mut Handler<'a> - 引用的生命周期与生命周期'a没有已知关系。错误告诉您这是无效的。您可以通过关联生命周期来修复错误。
fn push(&'a mut self)

然而,这并没有修复整个程序。


你的具体代码结构可能永远无法按照你想要的方式工作。你希望有一个处理程序引用列表,这些处理程序本身包含对处理程序的引用,所有这些引用需要拥有完全相同的生命周期。然而,你声明列表和处理程序的寿命是不同的,因为它们是分别声明的。
我不知道为什么你想要展示这种结构,但如果我需要它,我可能会将处理程序更改为使用Rc而不是&mut

谢谢提供这些信息 :) 我已经阅读了大部分内容,但是我还不知道如何实现它们 :D 顺便问一下,“我可能会使用Rc而不是&mut”是什么意思?我的代码中有Rc!你是说将列表定义为list: Rc<RefCell<Vec<Handler>>>吗?我一开始就这样做了,但遇到了这个错误:“self.list.borrow_mut().push(self) ^^^^ 期望结构体Handler,找到可变引用”。此外,您提到“它们都需要具有完全相同的生命周期”。实际上,我希望处理程序的寿命比列表短。这可能吗?再次感谢。 - hadilq
2
@hadilq 我的意思是我不会使用可变引用(&mut),而是会使用 Rc<RefCell<T>> https://play.integer32.com/?gist=229b0de1f84cdce9ee02cba26bbe30e5&version=nightly - Shepmaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接