I was working on a big file but this is a small toy example that causes the same issue. Sorry if the example itself makes no sense.
#![feature(nll)]
struct S(i32);
impl S {
fn foo(&mut self) -> Option<&i32> {
if let Some(val) = self.bar() {
return Some(val);
}
let y = &mut self.0;
None
}
fn bar(&mut self) -> Option<&i32> {
None
}
}
fn main() {
S(0).foo();
}
This doesn't pass the borrow checker:
error[E0499]: cannot borrow `self.0` as mutable more than once at a time
--> test.rs:9:17
|
6 | if let Some(val) = self.bar() {
| ---- first mutable borrow occurs here
...
9 | let y = &mut self.0;
| ^^^^^^^^^^^ second mutable borrow occurs here
|
note: first borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 5:5...
--> test.rs:5:5
|
5 | / fn foo(&mut self) -> Option<&i32> {
6 | | if let Some(val) = self.bar() {
7 | | return Some(val);
8 | | }
9 | | let y = &mut self.0;
10| | None
11| | }
| |_____^
Shouldn't this be valid (even without #![feature(nll)]
) since it is returning in the if let
block? It's worth noting that if I change the if let
block to the following, it compiles fine
if self.bar().is_some() {
return self.bar();
}