I'm reading through the "Learn rust" tutorial, and I'm trying to understand lifetimes. Chapter 10-3 has the following non-working example:
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
The paragraph below explains the error as :
When we’re defining this function, we don’t know the concrete values that will be passed into this function, so we don’t know whether the if case or the else case will execute.
However, if I change the block of code to do something else; say, print x and return y; so that we know what is being returned each time, the same error occurs. Why?
fn longest(x: &str, y: &str) -> &str {
println!("{}", x);
y
}
It book also says :
The borrow checker can’t determine this either, because it doesn’t know how the lifetimes of x and y relate to the lifetime of the return value.
My doubts are:
- Is the borrow checker capable of tracking lifetimes across functions? If so, can you please provide an example?
- I don't understand the error. x and y are references passed into
longest
, so the compiler should know that its owner is elsewhere(and that its lifetime would continue beyondlongest
). When the compiler sees that the return values are either x or y, why is there a confusion on lifetimes?