Move Closures Own Their Captured State
Build a counter factory whose move closure takes ownership of the captured count, so each returned closure carries independent mutable state between calls.
Code
fn new_counter() -> impl FnMut() -> i32 {
let mut count = 0;
// move 取得 count 的所有权:闭包自带状态,调用间保持
move || {
count += 1;
count
}
}
fn main() {
let mut first = new_counter();
let mut second = new_counter();
// 两个闭包各自持有独立的计数
let a = first();
let b = first();
let c = first();
println!("first: {}, {}, {}", a, b, c);
let d = second();
let e = second();
println!("second: {}, {}", d, e);
// 捕获的是变量本身:闭包里修改,外部读得到
let mut total = 0;
let mut add = |x: i32| {
total += x;
total
};
let after_five = add(5);
let after_two = add(2);
println!("add(5) = {}, add(2) = {}", after_five, after_two);
println!("total now: {}", total);
}Inside the code
Under the hood: the functions new_counter and main.
Caveats
- No package manager involved — every call resolves to a built-in API.
Applying it
The working signature is fn new_counter() -> impl FnMut() -> i32
Look for the first:, second:, add(5) = prefixes across the output; the prefixes name their steps.
Launch the file; main takes over and steps through new_counter.
Lines worth quoting
fn new_counter() -> impl FnMut() -> i32 {
let mut count = 0;
// move 取得 count 的所有权:闭包自带状态,调用间保持
move || {
count += 1;
count
}
}
Interactive Tools for This Topic
FAQ
- What does Move Closures Own Their Captured State print when run?
- The script runs standalone; its 4 labeled outputs include `first:`, `second:`, `add(5) =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.