Return Closures With impl Fn And move
Return closures from functions with impl Fn plus move, capturing state into the closure instead of borrowing stack locals that would not outlive the call.
Code
// 返回闭包必须 impl Fn + move:把捕获的 n 一起移进闭包
fn make_adder(n: i64) -> impl Fn(i64) -> i64 {
move |x| x + n
}
// FnMut 允许多次调用并修改捕获的内部状态
fn make_counter(start: i64) -> impl FnMut() -> i64 {
let mut current = start;
move || {
current += 1;
current
}
}
fn main() {
let add10 = make_adder(10);
println!("add10(5) = {}", add10(5));
println!("add10(7) = {}", add10(7));
let mut tick = make_counter(0);
println!("tick: {} {} {}", tick(), tick(), tick());
}How the snippet works
The compressed view: all the work sits in the functions make_adder, make_counter and main, doing all the work.
Applying it
The primary signature, spelled out, is fn make_adder(n: i64) -> impl Fn(i64) -> i64
The demo output is labeled (add10(5) =, add10(7) =, tick:), so each line traces straight back to the statement that printed it.
Treat main as the orchestrator calling make_adder and make_counter in a fixed order.
Statements that matter
fn make_counter(start: i64) -> impl FnMut() -> i64 {
let mut current = start;
move || {
current += 1;
current
}
}
fn make_adder(n: i64) -> impl Fn(i64) -> i64 {
move |x| x + n
}
Interactive Tools for This Topic
FAQ
- What does Return Closures With impl Fn And move print when run?
- Invoke the file as-is — the `add10(5) =`, `add10(7) =`, `tick:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.