What is the "the anonymous lifetime #1" and how can I define it in the right way?

Viewed 3956

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?

1 Answers

What is the "the anonymous lifetime #1"

"Anonymous" means something without a name. Lifetimes are things associated with references. Where are the references on line 14?

fn push(&mut self)
//      ^ here

Due to lifetime elision, you don't have to have an explicit lifetime, allowing it to be implicit (and anonymous).

Your code requires that the Vec contains &'a mut Handler<'a>, but you are trying to put in a &mut Handler<'a> — the lifetime of the reference has no known relation to the lifetime 'a. The error is telling you this is invalid. You can fix this error by relating the lifetimes:

fn push(&'a mut self)

This doesn't fix the entire program, however.


Your specific code structure will probably never work the way you want it to. You want to have a list of references to handlers that themselves contain references to handlers and all of these need to have exactly the same lifetime. However, you then declare that the list and handlers all live for different durations as they are declared separately.

I don't know why you'd want the structure you show, but if I needed it I'd probably switch to Rc for the handlers instead of &mut.

Related