Lifetime may not live long enough impl struct

Hi. I'm trying to solve the following error.

Could you tell me why this error happens?

My newbie brain thinks like:
Why self's lifetime > 's? Bstruct dropped in the end of the method.

Thank you in advance.

Code:


struct Data<'s>(Option<&'s [String]>);

struct AStruct<'s> {
    r: Option<Data<'s>>,
}

impl<'s> AStruct<'s> {
    fn do_something(&mut self) {

        self.do_mutable();

        self.do_immutable();

    }

    fn do_mutable(&mut self) {
        BStruct{
            mut_r:self.r.as_mut().unwrap(),
        };
        
    }

    fn do_immutable(&self) {

    }
}


struct BStruct<'s> {
    mut_r: &'s mut Data<'s>,
}

impl<'s> BStruct<'s> {
    fn run(&mut self) {
        &mut self.mut_r;
    }
        
}


fn main() {
    
}

Error:

error: lifetime may not live long enough
  --> src/main.rs:19:19
   |
8  | impl<'s> AStruct<'s> {
   |      -- lifetime `'s` defined here
...
17 |     fn do_mutable(&mut self) {
   |                   - let's call the lifetime of this reference `'1`
18 |         BStruct{
19 |             mut_r:self.r.as_mut().unwrap(),
   |                   ^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'s`
1 Like

Fixing the definition of Bstruct like below solved it

struct BStruct<'f, 's> {
    mut_r: &'f mut Data<'s>,
}

A &'s mut Thing<'s> means "exclusively borrow the Thing for the rest of its existence".

The reasons are the combination of

  • Thing<'s> is not valid outside of 's
  • &mut T is invariant in T, so if you create a &mut Thing<'s> it can't be coerced to &mut Thing<'shorter_than_s>
  • &'s mut T means "borrow T exclusively for 's"
5 Likes