fn (lowercase) is a function pointer — a concrete type representing a specific function address. Fn (uppercase) is a trait — an abstraction that any callable (closures, functions, function pointers) can implement.
fn — function pointer type:
fn(i32) -> i32.1fn square(x: i32) -> i32 {2 x * x3}45let f: fn(i32) -> i32 = square;6println!("{}", f(5)); // 2578// Can be stored in collections9let operations: Vec<fn(i32) -> i32> = vec![square, |x| x + 1];
Fn — closure trait:
Box<dyn Fn(i32) -> i32> for type-erased storage).1let name = "World";2let greet = || format!("Hello, {}!", name); // implements Fn3println!("{}", greet()); // Hello, World!45fn do_twice<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {6 f(f(x))7}8println!("{}", do_twice(|x| x + 1, 5)); // 7910// FnMut — closure that modifies captured state11let mut count = 0;12let mut counter = || { count += 1; count }; // implements FnMut13println!("{}", counter()); // 114println!("{}", counter()); // 2
When to use fn:
When to use Fn/FnMut/FnOnce:
.map(), .filter(), .sort_by()).Common mistakes: