Rust Reference ยท Core Traits
The Fn, FnMut and FnOnce traits
Reference for Rust Fn, FnMut and FnOnce: how closures capture variables, which trait each closure gets, bounds in generics, Box<dyn Fn> and returning closures.
Fn, FnMut and FnOnce are the three traits that describe things you can call: closures, function items and function pointers. They differ in what the call does to the captured state. FnOnce may consume it, so it can be called once. FnMut may change it, so it can be called many times but needs &mut access. Fn only reads it, so it can be called any number of times, even from several places at once.
The traits form a chain: every Fn is also FnMut, and every FnMut is also FnOnce. Because of that, a function that asks for FnOnce accepts the widest range of callers, and one that asks for Fn is the most restrictive. The compiler picks the traits for each closure automatically by looking at how its body uses the captured variables.
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 { f(x) }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait FnOnce<Args> { type Output; extern "rust-call" fn call_once(self, args: Args) -> Self::Output; } pub trait FnMut<Args>: FnOnce<Args> { extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output; } pub trait Fn<Args>: FnMut<Args> { extern "rust-call" fn call(&self, args: Args) -> Self::Output; }
You write the sugared form in bounds and types:
F: Fn(A, B) -> R F: FnMut(A) Box<dyn FnOnce() -> R + Send> impl Fn(i32) -> i32
| Trait | Call receives | Can be called | Typical closure body |
|---|---|---|---|
Fn |
&self |
any number of times, shared | only reads captures |
FnMut |
&mut self |
many times, one caller at a time | changes captures |
FnOnce |
self |
exactly once | moves a capture out or drops it |
Returns: the closure's result, -> R in the sugared syntax (the associated Output; omitted means ()).
Errors / panics / edge cases: you cannot implement these traits yourself on stable Rust; only closures, function items and pointers get them. Calling a FnMut through a non-mut binding is a compile error.
Usage notes
- Capture mode and trait are different things.
movedecides how variables are captured (by value). The trait depends on what the body does with them. Amoveclosure that only reads its data is stillFn. - Accept the weakest bound that works. Use
FnOnceif you call the closure once (likeOption::maporthread::spawn),FnMutfor repeated calls (likeIterator::map), andFnonly when you must share it, for example across threads. - Bound by value or by reference.
fn run(f: impl Fn())takes it by value;fn run(f: &dyn Fn())and&impl Fn()take a borrow. A&FisFnwheneverFisFn, and&mut FisFnMutwheneverFisFnMut. - Return types need
implorBox<dyn>. Each closure has a unique unnameable type, so write-> impl Fn(i32) -> i32or box it. Box<dyn FnOnce()>is callable directly, which makes it the usual type for queues of jobs.- Function items and
fnpointers (non-capturing closures coerce to them) implement all three, somap(double)works. - Thread and async needs.
thread::spawnrequiresFnOnce + Send + 'static; callbacks shared between threads needFn + Send + Sync. - Generics compile to static dispatch and can be inlined.
dyn Fnuses a vtable call, trading a little speed for flexibility.
Related
closureexpressions,move,dyn, Function pointers- Lessons: Closures, Trait objects, Threads