struct Foo {
a: Vec<i32>,
}
impl Foo {
fn bar(&mut self) -> &i32 {
if let Some(x) = self.a.iter().find(|i| **i == 0) {
return x;
}
self.a.push(0);
self.a.last().unwrap()
}
}
This code looks semantically correct to me. It should either return a reference to an existing element in the vector or create a new element and return a reference to it. But I get the following error:
error[E0502]: cannot borrow `self.a` as mutable because it is also borrowed as immutable
--> src/lib.rs:10:9
|
6 | fn bar(&mut self) -> &i32 {
| - let's call the lifetime of this reference `'1`
7 | if let Some(x) = self.a.iter().find(|i| **i == 0) {
| ------ immutable borrow occurs here
8 | return x;
| - returning this value requires that `self.a` is borrowed for `'1`
9 | }
10 | self.a.push(0);
| ^^^^^^^^^^^^^^ mutable borrow occurs here
Is there a way to make this code compile?