`|a: &()| a` doesn't compile

As the title says. Why doesn't this compile while fn func(a: &()) -> a { a } does?

fn main() {
    let _ = |a: &()| a;
}

(Playground)

Errors:

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

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

That is not valid rust code. Are you sure that it works?

1 Like

Sorry, updated!

Discussed in depth in Shouldn't lifetime elision apply to closure return type annotation? · Issue #56537 · rust-lang/rust · GitHub

This should explain several inconsistencies between fn's and closures I faced when working with async code.

1 Like