Fn FnMut and FnOnce
Quick answer
Rust describes callable closures using three related traits. Choose the weakest requirement that matches how your API needs to call its argument.
Callable contracts
Fn can be called through a shared reference, FnMut through a mutable reference, and FnOnce by consuming the callable. Fn closures also implement FnMut and FnOnce; FnMut closures also implement FnOnce. The closure body determines which contracts it satisfies.
fn twice(mut f: impl FnMut()) { f(); f(); }fn main() { let mut count = 0; twice(|| count += 1); println!("{count}");}Expected stdout (not executed):
2The callback changes its captured state.
fn once(f: impl FnOnce() -> String) -> String { f() }fn main() { let s = String::from("done"); println!("{}", once(move || s));}Expected stdout (not executed):
doneReturning the captured String moves it out of the closure.
Common mistake
Do not require Fn when an API can accept FnMut or calls its argument just once.
Try it yourself
Write a function that invokes a Fn callback twice and returns both results in a tuple.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Fn FnMut and FnOnce — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
An API calls a callback once and never uses it again. Which bound is least restrictive?
Fn FnMut and FnOnce — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn twice(mut f: impl FnMut()) { f(); f(); } fn main() { let mut count = 0; twice(|| count += 1); println!("{count}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Fn FnMut and FnOnce — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn once(f: impl FnOnce() -> String) -> String { f() } fn main() { let s = String::from("done"); println!("{}", once(move || s)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.