This doesn't make much sense because it returns the same thing regardless of the if let
, but it is a concise example of the problem that I am running into:
struct Data {
value: Option<i32>,
}
impl Data {
fn get(&mut self) -> Option<&mut i32> {
if let Some(val) = &mut self.value {
return Some(val);
}
return self.value.as_mut();
}
}
This code produces the error:
error[E0499]: cannot borrow `self.value` as mutable more than once at a time
--> src/lib.rs:11:16
|
6 | fn get(&mut self) -> Option<&mut i32> {
| - let's call the lifetime of this reference `'1`
7 | if let Some(val) = &mut self.value {
| --------------- first mutable borrow occurs here
8 | return Some(val);
| --------- returning this value requires that `self.value` is borrowed for `'1`
...
11 | return self.value.as_mut();
| ^^^^^^^^^^ second mutable borrow occurs here
I don't understand why this is a second mutable borrow when the first one goes out of scope before the second one will ever occur.
The val
variable is not in scope after the if let
, so how is this a second borrow? The first borrow should have already been released.
Just to be completely sure, I even surrounded the if let
with another block:
{
if let Some(val) = &mut self.value {
return Some(val);
}
}
return self.value.as_mut();
This produced the same error. What is going on here?