The code is as follows:
fn inner<'a:'b, 'b>(x:&'a i32, _y:&'b i32) -> &'b i32 {
x
}
fn main() {
let a = 1;
{
let b = 2;
inner(&b, &a);
inner(&a, &b);
}
}
The bound 'a:'b
in function inner
means that the lifetime 'a
lasts longer than 'b
. In the above example, the lifetime of variable b
is shorter then a
. The borrow checker should fail when encountering inner(&b, &a)
. However, the code can compile. Can someone provide some explanations?
Lifetimes are what the Rust compiler uses to keep track of how long references are valid for. Checking references is one of the borrow checker's main responsibilities. Lifetimes help the borrow checker ensure that you never have invalid references.
A generic lifetime parameter imposes a lifetime constraint on the reference(s) and the return value(s) of a function. While compiling the code, a generic lifetime is substituted for a concrete lifetime, which is equal to the smaller of the passed references' lifetimes.
The 'a reads 'the lifetime a'. Technically, every reference has some lifetime associated with it, but the compiler lets you elide (i.e. omit, see "Lifetime Elision") them in common cases. fn bar<'a>(...) A function can have 'generic parameters' between the <> s, of which lifetimes are one kind.
Lifetime annotations describe the lifetimes of the borrows, not of the borrowed variables. In both calls to inner()
, all borrows last until the end of the call, so the compiler can infer identical lifetimes for them, so the bound 'a: 'b
is fulfilled in both cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With