tags: rust, programming, systems
“When we pass concrete references to longest, the concrete lifetime that is substituted for 'a is the part of the scope of x that overlaps with the scope of y. In other words, the generic lifetime 'a will get the concrete lifetime that is equal to the smaller of the lifetimes of x and y. Because we’ve annotated the returned reference with the same lifetime parameter 'a, the returned reference will also be valid for the length of the smaller of the lifetimes of x and y.”
fn main() {
let string1 = String::from("long string is long");
{//-------------------------------------------------------------a
let string2 = String::from("xyz");
let result = longest(string1.as_str(), string2.as_str());
println!("The longest string is {result}");
}//--------------------------------------------------------------
}while i don’t agree with the way the book represents it. I’d like to think of the lifetimes as how long does the main object last, not the reference to it.
So basically when i say a function has parameter with lifetime 'a and outputs a lifetime with 'a, it means that the output can be valid as long as the main object the parameters were referencing to is valid or alive.
fn test<'a>(x: &'a String, y: &'a String) -> &'a String {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let x = String::from("this is a test");
let y = String::from("this is another test");
let t;
{
let f = &x;
let x = &y;
t = test(f);
}
println!("{:?}", t);
}my explanation can be proved above