Rust Closures and lambda expressions Returning lambdas from functions


Returning lambdas (or closures) from functions can be tricky because they implement traits and thus their exact size is rarely known.

// Box in the return type moves the function from the stack to the heap
fn curried_adder(a: i32) -> Box<Fn(i32) -> i32> {
    // 'move' applies move semantics to a, so it can outlive this function call
    Box::new(move |b| a + b)

println!("3 + 4 = {}", curried_adder(3)(4));

This displays: 3 + 4 = 7