I'm currently learning Rust from the the book 'The Rust Programming Language' and seemingly I've encountered the following:
fn main() {
let mut s = String::from("Hello");
let mut add_suffix = || s.push_str(" world");
println!("{s}");
add_suffix();
}
results in the compiler error:
error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable
--> src/main.rs:4:16
|
3 | let mut add_suffix = || s.push_str(" world");
| -- - first borrow occurs due to use of `s` in closure
| |
| mutable borrow occurs here
4 | println!("{s}");
| ^ immutable borrow occurs here
5 | add_suffix();
| ---------- mutable borrow later used here
|
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
What I've understood is that add_suffix
somehow took a mutable reference to s
(I know that push_str
requires a mutable reference) and thus increases the lifetime of add_suffix
to start on the closure definition and ends on the call.
But I don't seem to understand why is that happening before we call the closure (namely add_suffix
), why does Rust enforce that and what's unsafe about that? If we imagine the lifetime of that mutable reference starts and ends on the the call I can't see a way where that go wrong.