-2

Can somebody help me to understand why the code can run ? How can a method return local temp references out of the scope?

fn test_Borrowing3<'a>() -> Vec<&'a i32>
{
        let a: &i32 = &1;
        let b = &2;
        let aa = vec![a, b];
        return aa
}
Ken
  • 41
  • 1
  • The answer linked by @Netwave addresses the "reference to constant" thing but returns a `'static` type. This question has the additional `'a` lifetime. The explanation is that a `'static` lifetime lives as long as any other lifetime, so this conversion is allowed (covariance!). – rodrigo Oct 26 '21 at 08:21
  • @rodrigo, for some reason I read can't, too early, need more coffee :D – Netwave Oct 26 '21 at 08:23
  • @Netwave: Oh, I wasn't criticizing your duplicate, actually I think it was mostly appropriate, I was just commenting this little difference. – rodrigo Oct 26 '21 at 08:36

1 Answers1

1

As @rodrigo pointed, your lifetime 'a is a generic lifetime which in this case is converted to a 'static one, could be similar to:

fn test_Borrowing3() -> Vec<&'static i32>
{
    let a: &i32 = &1;
    let b = &2;
    let aa = vec![a, b];
    return aa
}

Playground

For extended explanations see also:

Is there any way to return a reference to a variable created in a function?

Specifically this answer from @LukasKalbertodt explains it perfectly.

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • It’s more that `'static` is converted to `'a` than the other way around: the caller gets to determine `'a`, and it happens that the actual references being returned are `'static`, which can be converted to `'a`. – eggyal Oct 26 '21 at 11:05
  • @eggyal, well, the lifetime is promoted to the valid one, in this case 'static. Maybe I didn't express it well, or I do not know how to express it though. – Netwave Oct 26 '21 at 11:07