Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Rust combine its multiple lifetime?

Tags:

rust

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?

like image 922
Frank Sheng Avatar asked Mar 31 '21 06:03

Frank Sheng


People also ask

How does lifetime work in Rust?

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.

What is a lifetime parameter rust?

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.

WHAT IS A in Rust?

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.


1 Answers

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.

like image 151
Sven Marnach Avatar answered Nov 15 '22 07:11

Sven Marnach