实现说明
除了函数 new_counter、main,文件里再无其他定义。
使用要点
- 跑完文件,输出里会留下标记——
first:、second:、add(5) =。 - 执行文件,
main会按顺序走完new_counter。
常见问题
运行「move 闭包拥有捕获的状态」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 first:、second:、add(5) = 这类标签。
主要签名是 fn new_counter() -> impl FnMut() -> i32
核心语句
fn new_counter() -> impl FnMut() -> i32 {
let mut count = 0;
// move 取得 count 的所有权:闭包自带状态,调用间保持
move || {
count += 1;
count
}
}
代码示例
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);
}