5

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?

Giacomo Pirinoli
  • 548
  • 6
  • 17
Frank Sheng
  • 195
  • 7
  • Does this answer your question? [what is the difference between this rust function about lifetime](https://stackoverflow.com/questions/60964731/what-is-the-difference-between-this-rust-function-about-lifetime) – Jmb Mar 31 '21 at 07:18
  • @Jmb To me that question looks quite different. – Sven Marnach Mar 31 '21 at 07:22
  • @SvenMarnach but the answer to that question also applies to this one. TLDR: if a function parameter has lifetime `'a`, this means that the passed reference must live _at least_ as long as `'a`, not _exactly_ as long as `'a`. – Jmb Mar 31 '21 at 08:21

1 Answers1

4

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.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841