I want the Handler below to push itself into the list
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
}
but I faced this error and I cannot find a way to pass it!
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 | | }
| |_____^
What is the "the anonymous lifetime #1" and how can I define it in the right way? Or even, is my approach correct to this problem in Rust?