I'm just getting into Rust, so another beginner question... I've been doing stuff like the code below in C++ a lot. I'll use a closure as an inner helper function that captures local variables. But in Rust the rules don't let me do this. How would you get around this error?
It seems to me that finish()
doesn't actually borrow my_str
until finish
runs. But it seems Rust considers it borrowed when the closure is constructed, so the mutable borrow with push_str
can't happen.
fn closure_capture_example() {
let mut my_str = String::new();
let finish = || -> i32 {
let n = my_str.parse().unwrap();
println!("finishing, parsing i32: {n}");
n
};
my_str.push_str("123");
let i = finish();
println!("done, i = {i}")
}
The error is:
error[E0502]: cannot borrow `my_str` as mutable because it is also borrowed as immutable
156 | let finish = || -> i32 {
| --------- immutable borrow occurs here
157 | let n = my_str.parse().unwrap();
| ------ first borrow occurs due to use of `my_str` in closure
...
161 | my_str.push_str("123");
| ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
162 | let i = finish();
| ------ immutable borrow later used here