What Is the Difference Between a Closure and a Function Pointer in Rust?

Closures capture their environment and are anonymous, while function pointers reference named functions without capturing context.

A closure is an anonymous function that can capture variables from its surrounding environment, while a function pointer is a reference to a named function that cannot capture any context. Closures are used for inline logic and callbacks that need access to local state, whereas function pointers are used when you need to pass a standard function to another function or store it in a struct field.

// Closure: Captures 'x' from the environment
let x = 10;
let add_x = |n| n + x;
println!("{}", add_x(5)); // Prints 15

// Function pointer: No capture, must be a named function
fn add_five(n: i32) -> i32 {
    n + 5
}
let fp: fn(i32) -> i32 = add_five;
println!("{}", fp(5)); // Prints 10