Do references to long lifetime `a` behind short lifetime `b` reference survive when `b` drops?

If I have a vector of captured references of lifetime 'a and a reference to that vector of lifetime 'b.

let a // vector of references
let b  = a.as_ref()

If lifetime 'b was a closure, I wouldn't be able to save references from lifetime 'a in a new vector created outside the closure because they'll get dropped - lifetime 'a will coerce to lifetime 'b?

When I inspect lifetime 'a through a reference in a short lifetime 'b context, I see that lifetime 'a lasts as long as lifetime 'b.

If you have a closure that borrows a Vec<&'a T>, then that closure cannot outlive 'a, as you said. However, that closure could return an &'a T if it wanted, it's okay for the return value of a closure to outlive the closure.

I didn't really understand what you mean by "save references from lifetime 'a in a new vector created outside the closure". I think it will make a lot more sense to you if instead of thinking about how you would syntactically represent it, you just focus on when things will be dropped, and see if it happens in the right order. Values are dropped when the scope they are owned in ends, so if your borrow ends before that happens then your code is most likely correct. The purpose of annotating lifetimes is mostly just so that the compiler knows which borrow you're depending on in the return type, so it knows how long the return type will survive.

Here's a working example showing that the longer reference does survive:

fn f<'long, 'short, T>(slice: &'short [&'long T]) -> &'long T {

fn main() {
    let s = String::from("123"); // 'long starts
    let first = {
        let vec = vec![&s]; // 'short starts
    }; // 'short ends
    println!("{}", first);
} // 'long ends
1 Like

Yes, this question is difficult to explain. The code seems to address the issue but I will get a minimal example to correctly explain.

This answers the question. My issue was something else.

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.