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)
{
    &double
}

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

And I get this error:

src\main.rs:8:6: 8:12 error: borrowed value does not live long enough
src\main.rs:8     &double
                   ^~~~~~
note: reference must be valid for the static lifetime...
src\main.rs:7:1: 9:2 note: ...but borrowed value is only valid for the block at 7:0
src\main.rs:7 {
src\main.rs:8     &double
src\main.rs:9 }
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 {
    double
}
2 Likes

thanks

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

Note:
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.

1 Like