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
This example demonstrates how to use returning closures in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the functions category to build a complete understanding of this topic.