问题描述
我无法理解这里关于 Rust 闭包的概念。在我的代码计数中,默认值为 i32
。当我创建可变闭包时,它将获取其中使用的变量的可变引用,如文档中所述。
当我在循环中调用 inc 闭包并尝试在循环内打印计数值时,我会得到可变借用使用错误,但如果我在循环外打印计数值,那就没问题了。即使在循环中,当我在打印宏 inc()
超出范围之前调用 inc()
闭包时,它为什么会引发错误。
fn main() {
let mut count = 0;
let mut inc = || {
count += 2;
};
for _index in 1..5 {
inc();
println!("{}",count);
}
}
解决方法
当您创建闭包时,它会可变地借用 count
变量。当可变借用处于活动状态时(包括 count
变量本身),禁止通过另一个引用访问 count
变量。当不再使用闭包时,它会被删除,此时它会释放借用,这使得再次访问 count
成为可能。
fn main() {
let mut count = 0;
let mut inc = || {
count +=2;
};
// Now we can't access `count`
for _index in 1..5 {
inc();
// println!("{}",count);
// Here we can't access `count` because it is borrowed mutably by `inc`
}
// Here `inc` is dropped so `count` becomes accessible again
println!("{}",count);
}