In this github discussion you find this code that draws the ire of the borrow checker:
fn main() {
let mut vec = vec!();
match vec.first() {
None => vec.push(5),
Some(v) => unreachable!(),
}
}
I understand why having a mutation while immutable borrows are outstanding is problematic. I assumed that a solution was to explicitly only have one borrow (a mutable one) but it still resulted in my having two borrows, an immutable borrow and then a mutable borrow:
fn main() {
let mut vec: Vec<i32> = vec!();
let r_vec: &mut Vec<i32> = &mut vec;
match r_vec.first() {
None => r_vec.push(5),
Some(v) => unreachable!(),
}
}
The compiler is still not happy:
error[E0502]: cannot borrow `*r_vec` as mutable because it is also borrowed as immutable
--> testrust.rs:7:17
|
6 | match r_vec.first() {
| ----- immutable borrow occurs here
7 | None => r_vec.push(5),
| ^^^^^ mutable borrow occurs here
8 | Some(v) => unreachable!(),
9 | }
| - immutable borrow ends here
Why does my workaround not work, and what is the proper way to get around this issue?