RRust By Example
advancedFunctions

Returning Closures

Return closures from functions using impl Fn or Box<dyn Fn>.

Returning Closures

Return closures from functions using impl Fn or Box.

Difficulty

Advanced

Code

rust
fn make_greeting(name: String) -> impl Fn() {
    move || println!("Hello, {}!", name)
}

fn make_operation(op: &str) -> Box<dyn Fn(i32, i32) -> i32> {
    match op {
        "add" => Box::new(|a, b| a + b),
        "mul" => Box::new(|a, b| a * b),
        _ => Box::new(|a, b| a - b),
    }
}

fn main() {
    let greet = make_greeting(String::from("Rust"));
    greet();

    let add = make_operation("add");
    println!("result: {}", add(3, 5));
}

Explanation

Return closures with impl Fn or Box.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the functions category to build a complete understanding of this topic.

More Functions Examples