fn main() {
let mut a = String::from("a");
let closure = || {
a.push_str("b");
};
closure();
}
This won't compile:
error[E0596]: cannot borrow immutable local variable `closure` as mutable
--> src/main.rs:7:5
|
3 | let closure = || {
| ------- consider changing this to `mut closure`
...
7 | closure();
| ^^^^^^^ cannot borrow mutably
If I return a
in the closure without adding mut
, it can be compiled:
fn main() {
let mut a = String::from("a");
let closure = || {
a.push_str("b");
a
};
closure();
}
This confuses me a lot. It seems like when I call closure()
, closure
will be borrowed if something is mutable inside it. Why won't it be borrowed when I return a
?