#![allow(unused)]
fn main() {
let outer_ok = "outer".to_owned();
let outer_ref_ok: &str = &outer_ok;
let my_ref: &str;
{
let inner_ok = "inner".to_owned();
let inner_ref_ok: &str = &inner_ok;
test_lifetime1(inner_ref_ok, outer_ref_ok); // OK! But why? ****
test_lifetime2(outer_ref_ok, inner_ref_ok); // OK
my_ref = test_lifetime3(inner_ref_ok, outer_ref_ok);
}
println!("{outer_ref_ok}"); // OK, print: "outer"
// println!("{my_ref}"); // ERROR if uncommented: `inner_ok` dropped after the bracket while still borrowed
}
fn test_lifetime1<'a, 'b, T>(outer: &'a T, inner: &'b T) where T: ?Sized, 'a: 'b {}
fn test_lifetime2<'a, T>(outer: &'a T, inner: &'a T) where T: ?Sized {}
fn test_lifetime3<'a, 'b, T>(outer: &'a T, inner: &'b T) -> &'a T where T: ?Sized, 'a: 'b {outer}
In this code snippet, I wonder why is test_lifetime1
allowed by the borrow checker and works well, for I specified that 'a is longer - or at least as long as 'b in official terms. I think the borrow checker should first annotate all the variables their lifetime and then it will notice that outer_ok
has a larger scope than inner_ok
and that inner_ok
definitely isn't as long as outer_ok
but is strictly shorter than it, which violates the constraint. I have one speculation. All the usages of this syntax is related to some struct
and their reference field after my looking up some references. So maybe using it in this trivial circumstance is ignored by the borrow checker. But I don't know if this is the case.