The function signature
fn f<'a>(x: &'a i32) -> &'a i32;
means that the value returned by f
is a reference to what x
parameter refers to, hence it can't outlive it. For example, this won't work:
// Compile error
let y = {
let x = 0;
f(&x)
// x is dropped here
};
// Here y still "exists", but x doesn't (y outlives x)
To your specific question:
Lets say I do the following then:
let x = 0;
let y = f(&x);
In that case, the Rust borrow checker considers y to borrow x. Why?
The answer is because the function signature of f
tells it so. To give you an example, suppose that we change the signature to this:
fn f<'a, 'b>(x: &'a i32, z: &'b i32) -> &'a i32;
Then we call f
like this:
let x = 0;
let z = 1;
let y = f(&x, &z);
In the code above, y
borrows x
, but not z
. It's because the return value of f
has 'a
lifetime that is the same as x
's lifetime.