我希望下面的
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 代码是否正确解决了这个问题?
Rc
而不是&mut
”是什么意思?我的代码中有Rc
!你是说将列表定义为list: Rc<RefCell<Vec<Handler>>>
吗?我一开始就这样做了,但遇到了这个错误:“self.list.borrow_mut().push(self) ^^^^ 期望结构体Handler
,找到可变引用”。此外,您提到“它们都需要具有完全相同的生命周期”。实际上,我希望处理程序的寿命比列表短。这可能吗?再次感谢。 - hadilq&mut
),而是会使用Rc<RefCell<T>>
https://play.integer32.com/?gist=229b0de1f84cdce9ee02cba26bbe30e5&version=nightly - Shepmaster