Returning reference to fn


I’m trying to make this program work:

fn double(x: i32) -> i32
    x * 2

fn get_double_func() -> &'static (Fn(i32) -> i32)

fn main()
    let f = get_double_func();
    println!("{}", f(10));

And I get this error:

src\ 8:12 error: borrowed value does not live long enough
src\     &double
note: reference must be valid for the static lifetime...
src\ 9:2 note: ...but borrowed value is only valid for the block at 7:0
src\ {
src\     &double
src\ }
error: aborting due to previous error

But I think double function lives in the whole program, not just only in that block.


The Fn type is for closures. To refer to the double function, use this syntax:

fn get_double_func() -> fn(i32) -> i32 {




You could do this with Fn(i32) -> i32 as well except for 2 things:

  • Closures as type parameters require generics
  • Returning generics is currently not supported hence the workarounds

Using Fn(i32) -> i32 is more advantageous than fn(i32) -> i32 because closures can also be used. With fn, closures cannot be used and so is more restrictive.