Inside a function, I am trying to push a value into a vector and afterwards return a reference to that value, which is inside the vector. Sadly, it doesn't work and I get the following error:
error[E0502]: cannot borrow `vector` as immutable because it is also borrowed as mutable
--> src\lib.rs:19:19
|
18 | let _unit_0 = push_and_get(&mut vector);
| ----------- mutable borrow occurs here
19 | let _unit_1 = vector.last().unwrap();
| ^^^^^^ immutable borrow occurs here
20 | drop(_unit_0);
| ------- mutable borrow later used here
Here's my code with two functions (this_works
, this_does_not_work
) which, to my understanding, do the same thing, but only one of them works.
fn this_works() {
let mut vector = Vec::new();
vector.push(());
let _unit_0 = vector.last().unwrap();
let _unit_1 = vector.last().unwrap();
}
fn this_does_not_work() {
let mut vector = Vec::new();
let _unit_0 = push_and_get(&mut vector);
let _unit_1 = vector.last().unwrap();
drop(_unit_0); // Added, to make the error reappear
}
fn push_and_get(vector: &mut Vec<()>) -> &() {
vector.push(());
vector.last().unwrap()
}
Is there any way to get the push_and_get
function to work or is it impossible, because of a limitation of Rust? If it's the first, how can I get it to work and if it's the latter, are there any plans to fix this particular issue or are there any good reasons why this shouldn't be fixed?