fn is a function pointer type (concrete, zero-cost). Fn is a trait (abstraction, flexible). fn is a type; Fn is a trait. Any function pointer satisfies the Fn trait.
fn — concrete function pointer:
fn(Args) -> Output.1fn add(a: i32, b: i32) -> i32 { a + b }2fn sub(a: i32, b: i32) -> i32 { a - b }34let ops: Vec<fn(i32, i32) -> i32> = vec![add, sub];5for op in ops {6 println!("Result: {}", op(10, 3));7}
Fn — callable trait:
1use std::collections::HashMap;23let mut cache: HashMap<String, Box<dyn Fn(i32) -> i32>> = HashMap::new();4let base = 10;5cache.insert("double".into(), Box::new(|x| x * 2));6cache.insert("add_base".into(), Box::new(move |x| x + base));78if let Some(f) = cache.get("double") {9 println!("{}", f(5)); // 1010}
When to use fn:
When to use Fn/FnMut/FnOnce:
Common mistakes: