I would like to get the last element of a vector and use it to determine the next element to push in. Here's an example how it doesn't work, but it shows what I'm trying to achieve:
let mut vector: Vec<i32> = Vec::new();
if let Some(last_value) = vector.last() {
vector.push(*last_value + 1);
}
I can't use push
while the vector is also borrowed immutably:
error[E0502]: cannot borrow `vector` as mutable because it is also borrowed as immutable
--> src/main.rs:5:9
|
4 | if let Some(last_value) = vector.last() {
| ------ immutable borrow occurs here
5 | vector.push(*last_value + 1);
| ^^^^^^ mutable borrow occurs here
6 | }
| - immutable borrow ends here
What would be a good way to do this?