intermediateFunctions
Higher-Order Functions
Functions that take or return other functions.
Higher-Order Functions
Functions that take or return other functions.
Difficulty
Intermediate
Code
rust
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(x)
}
fn make_adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}
fn main() {
let double = |x| x * 2;
println!("apply(double, 5) = {}", apply(double, 5));
let add_10 = make_adder(10);
println!("add_10(3) = {}", add_10(3));
}Explanation
This example demonstrates how to use higher-order functions 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.