In most cases, the Rust compiler can infer the lifetime. if the lifetime scope is determined at runtime, it says that the lifetime must be explicitly marked.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
Here,
- The lifetime is generic.
- This means that there is a scope bound to the lifetime 'a after the function result is returned.
- the compiler can know information that the memory is valid for the minimum lifetime 'a.
I'am very curious. instead of using a lifetime syntax, can't the compiler just adopt the fewer scope area to which lifetime 'a can be bound?
fn main() { //larger scope
let s1 = String::from("long string is long");
{ //fewer scope
let s2 = String::from("xyz");
let result = longest(s1.as_str(), s2.as_str());
println!("The longest string is {}", result);
}
}
Even if the call stack is more complex on the caller side, the scope area is determined at the time of borrowing, so the same question seems to be possible.
fn func1<'a>(x: &'a str, y: &'a str) {
let c = String::from("hello");
let result = func2 (a,b,c)
...
}