Function show_notes::e005::demonstrate_function_returns

source ·
pub fn demonstrate_function_returns()
Expand description

Uses the doubler_factory to get a function which doubles a number.

By contrast, here’s a function which simply won’t compile:

fn will_not_compile() -> Fn(i32) {
    let a_closure = |n| println!("Seriously. This won't compile. {}", n);
    a_closure
}

And another. This gets us a bit closer, because you actually have both a concrete reference type and a lifetime. However, it still won’t compile, because after get_normal_function_with_lifetime ends, the function goes out of scope and the reference points to junk value.

fn get_normal_function_with_lifetime() -> &'static (Fn(i32) -> i32) {
    fn multiply_by_3(n: i32) -> i32 {
        n * 3
    }

    return &multiply_by_3;
}

Even this approach doesn’t work, because although the function lives on past the end of the get_normal_external_fn_with_lifetime, the reference created during that function call doesn’t.

fn multiply_by_4(n: i32) -> i32 { n * 4 }

fn get_normal_external_fn_with_lifetime() -> &'static (Fn(i32) -> i32) {
    &multiply_by_4
}

The solution, as we saw at the beginning, is to use Box::new to heap-allocate the function result instead.