Hi, I'm trying to understand lifetimes better, and one thing I still don't fully understand is lifetime declaration at functions and structs.
I roughly understand that for functions, lifetimes describe a relation between the arguments passed to the function and the return value, and subtyping and variance is used to coerce all the lifetimes within a function body to the same value, which is then used down the line by the compiler. For instance:
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
I get that in this code, the input lifetimes as well as the output lifetime are coerced to the same lifetime through subtypes, so if x: &'a str and y: &'b str is passed into the function where 'a is a subtype of 'b, 'a is coerced to 'b and the return value must have a lifetime of 'b or a subtype of 'b.
However, in Rust By Example, the comment says that the reference must live as long as the function:
// One input reference with lifetime `'a` which must live
// at least as long as the function.
fn print_one<'a>(x: &'a i32) {
println!("`print_one`: x is {}", x);
}
It says the same thing for structs:
// A type `Borrowed` which houses a reference to an
// `i32`. The reference to `i32` must outlive `Borrowed`.
#[derive(Debug)]
struct Borrowed<'a>(&'a i32);
Question: Does the generic lifetime declaration in the function and struct definition imply some kind of relation between the lifetime of the function and struct, or does the compiler simply check that the lifetime of the arguments and values in the struct must be longer than the lifetime of the function and struct? i.e. Does the lifetime of the function and struct play any role in coercion of lifetimes, or is there just a simple verification to check that the coerced lifetime is longer than the function/struct lifetime?