fn (lowercase) is a function pointer type — it refers to a specific function in memory. Fn (uppercase) is a trait — it represents anything callable, including closures and function pointers.
fn — function pointer:
fn(i32) -> i32.1fn add(a: i32, b: i32) -> i32 {2 a + b3}45let f: fn(i32, i32) -> i32 = add; // Function pointer6println!("{}", f(2, 3)); // 578// Passing function pointer as argument9fn apply(f: fn(i32, i32) -> i32, a: i32, b: i32) -> i32 {10 f(a, b)11}12println!("{}", apply(add, 10, 20)); // 30
Fn — closure trait:
1let multiplier = 3;23// Closure captures `multiplier` from environment4let multiply = |x| x * multiplier; // implements Fn5println!("{}", multiply(5)); // 1567// fn CANNOT do this:8// fn bad(x: i32) -> i32 { x * multiplier } // Error!910// Fn trait as generic parameter11fn apply_twice<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {12 f(f(x))13}14println!("{}", apply_twice(|x| x + 1, 5)); // 7
When to use fn:
When to use Fn/FnMut/FnOnce:
Common mistakes: