How does Rust combine its multiple lifetime?

Viewed 148

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?

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.

Related