Closure Capture Fn FnMut And FnOnce
Capture closure state with Fn for repeated reads, FnMut for mutation across calls, and FnOnce when the body moves the captured value out.
Code
fn apply(value: i32, op: impl Fn(i32) -> i32) -> i32 {
op(value)
}
fn make_adder(step: i32) -> impl Fn(i32) -> i32 {
move |x| x + step
}
fn main() {
let base = 10;
// Fn:只读借用捕获(capture),可以反复调用
let report = || println!("base is {}", base);
report();
// FnMut:可变借用捕获,调用之间保留状态
let mut count = 0;
let mut tick = || {
count += 1;
count
};
let first = tick();
let second = tick();
println!("ticks: {} {}", first, second);
// FnOnce:调用时把捕获的 String 移出闭包体,只能调用一次
let label = String::from("job-42");
let finish = move || label;
let reclaimed = finish();
println!("reclaimed: {}", reclaimed);
// 闭包既可作为参数传入,也可作为返回值返回
println!("apply: {}", apply(5, |x| x * base));
println!("adder: {}", make_adder(3)(7));
}How the snippet works
The working surface is the functions apply, make_adder and main — everything else is wiring.
Using it
The primary signature is fn apply(value: i32, op: impl Fn(i32) -> i32) -> i32
The demo output is labeled (base is, ticks:, reclaimed:); each label names the call that printed it.
main sequences apply and make_adder; executing the file runs that flow once.
Key statements
fn apply(value: i32, op: impl Fn(i32) -> i32) -> i32 {
op(value)
}
fn make_adder(step: i32) -> impl Fn(i32) -> i32 {
move |x| x + step
}
let finish = move || label;
Interactive Tools for This Topic
FAQ
- What does Closure Capture Fn FnMut And FnOnce print when run?
- Invoke the file as-is — the `base is`, `ticks:`, `reclaimed:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.