2

Let's consider a closure that immediately returns the reference it gets from the argument.

fn main() {
    let closure = |x: &i32| x;
    println!("{}", closure(&42));
}

It doesn't work because the Rust compiler believes that the returning reference has no correlation with the argument reference.

   Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
 --> src/main.rs:2:29
  |
2 |     let closure = |x: &i32| x;
  |                       -   - ^ returning this value requires that `'1` must outlive `'2`
  |                       |   |
  |                       |   return type of closure is &'2 i32
  |                       let's call the lifetime of this reference `'1`

error: could not compile `playground` due to previous error

If we explicitly teach the compiler by manually annotating the type of the closure, it will work.

fn main() {
    let closure: for<'a> fn(&'a i32) -> &'a i32 = |x: &i32| x;
    println!("{}", closure(&42));
}

However, the lifetime elision rule states the following:

If there is exactly one input lifetime position (elided or not), that lifetime is assigned to all elided output lifetimes.

In which case the compiler should have concluded that '1 and '2 in the error message to be the same.

Is there a reason that the lifetime elision rule is not applicable to closure type inference?

Update:

An answer to a similar question confirms that the lifetime elision rule does not apply to the closure. But the question is why it does not apply.

Zhiyao
  • 4,152
  • 2
  • 12
  • 21

0 Answers0