When you create the closure, it borrows mutably the count
variable. It is forbidden to access the count
variable through another reference while the mutable borrow is alive (including the count
variable itself). The closure is dropped when it is no longer used, at which point it releases the borrow which makes it possible to access count
again.
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);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…