From comprehensive rust
the following is a borrowing error:
fn main() {
let mut a: i32 = 10;
let b: &i32 = &a;
{
let c: &mut i32 = &mut a;
*c = 20;
}
println!("a: {a}");
println!("b: {b}");
}
Output:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
--> src/main.rs:6:27
|
3 | let b: &i32 = &a;
| -- immutable borrow occurs here
...
6 | let c: &mut i32 = &mut a;
| ^^^^^^ mutable borrow occurs here
...
11 | println!("b: {b}");
| --- immutable borrow later used here
But why, because I was under the impression that variable c
lives only in the scope and no more afterwards, so why does rustc still complain on the last line, the mutable c
is not even accessible anymore at this point? Is rustc just not able to asses the fact that c
is no more available or this is not that easy for the borrow checker to assert??
The speaker notes do not even say a word on this, its kind of confusing :).