fn is a function pointer type — a concrete, zero-sized type pointing to a function. Fn is a trait — an abstraction implemented by closures, functions, and anything callable.
fn — concrete function pointer:
fn(i32, i32) -> i32.1fn multiply(a: i32, b: i32) -> i32 {2 a * b3}45let op: fn(i32, i32) -> i32 = multiply;6println!("{}", op(3, 4)); // 1278fn execute(f: fn(i32, i32) -> i32, x: i32, y: i32) -> i32 {9 f(x, y)10}11println!("{}", execute(multiply, 5, 6)); // 30
Fn — callable trait:
call(&self, args) -> Output.1let base = 100;2let add_base = |x| x + base; // Captures `base` — implements Fn3println!("{}", add_base(50)); // 15045// Generic function accepting Fn trait6fn apply<F: Fn(i32) -> i32>(f: F, value: i32) -> i32 {7 f(value)8}910println!("{}", apply(|x| x * 2, 21)); // 4211println!("{}", apply(add_base, 50)); // 15012println!("{}", apply(multiply_three, 3)); // 9 (if defined)
When to use fn:
When to use Fn/FnMut/FnOnce:
Common mistakes: