Why am I getting a error of "lifetime may not live long enough" when it does?

I am trying to write a destructor for a custom struct that calls a function reference stored in the struct, except the compiler says that the references in the struct will not live long enough.
Code:

pub struct Mut<'a,T,O>{
    raw_mut:&'a mut T,
    source :&'a O,
    dropper:&'a fn(&'a mut T,&'a O,)->(),
}
...
impl<'a,T,O> Drop for Mut<'a,T,O>{
    fn drop(self:&mut Mut<'a,T,O>)->(){
        (self.dropper)(self.raw_mut,self.source);
        //let _a:&mut Self = self;
        return;
    }
}

Any constructor argument must outlive the struct.

High chance you should change your code to

pub struct Mut<'a,T,O>{
    raw_mut:&'a mut T,
    source :&'a O,
    dropper:&'a fn(&mut T,&O,)->(),
}

impl<'a,T,O> Drop for Mut<'a,T,O>{
    fn drop(self:&mut Mut<'a,T,O>)->(){
        (self.dropper)(self.raw_mut,self.source);
        //let _a:&mut Self = self;
        return;
    }
}

In your original code, dropper accepts a &'a mut T, which you can't provide in drop. Since you cannot get a &'a mut T from &'b mut &'a mut T where b might be shorter than a.

2 Likes

Thank you.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.