8.7 Function Pointers and Higher-Order Functions

8.7.1 Function Pointers

You can pass functions as parameters using function pointers.

fn add_one(x: i32) -> i32 {
    x + 1
}
fn apply_function(f: fn(i32) -> i32, value: i32) -> i32 {
    f(value)
}
fn main() {
    let result = apply_function(add_one, 5);
    println!("Result: {}", result);
}
  • fn(i32) -> i32 is the type of a function that takes an i32 and returns an i32.

8.7.2 Higher-Order Functions

Functions that take other functions as parameters or return functions are called higher-order functions.

Note: Rust also has closures (anonymous functions), which will be discussed in a later chapter.