Capturing the Environment with Closures
Mutable? Immutable?
Problem Statement
fn main() {
let mut x = 0;
let counter = || {
x += 1; // IDE: cannot borrow `counter` as mutable, as it is not declared as mutable
x
};
println!("{}", counter()); // IDE: cannot borrow as mutable
}$ cargo run
Compiling counter v0.1.0 (file:///projects/counter)
error[E0596]: cannot borrow `counter` as mutable, as it is not declared as mutable
--> src/main.rs:7:20
|
3 | let counter = || {
| ------- help: consider changing this to be mutable: `mut counter`
4 | x += 1;
| - calling `counter` requires mutable binding due to mutable borrow of `x`
...
7 | println!("{}", counter());
| ^^^^^^^ cannot borrow as mutable
For more information about this error, try `rustc --explain E0596`.
error: could not compile `counter` due to previous errorResolution
Conclusion
Reference
Last updated