Here, I have a struct Bar
that has a reference to Foo
in it. I recently got an error that matched this pattern and wanted to try and create a reproducible example.
struct Bar<'a> {
foo: &'a Foo,
}
struct Foo;
impl Foo {
fn borrow_mut(&mut self) {
unimplemented!()
}
fn create_option_bar(&self) -> Option<Bar> {
unimplemented!()
}
fn create_bar(&mut self) -> Bar {
let option_bar = self.create_option_bar();
if option_bar.is_some() {
return option_bar.unwrap();
}
self.borrow_mut();
unimplemented!()
}
}
so... this doesn't compile but, if i do something like this
fn can_guarantee_option_bar_will_be_some() -> bool {
unimplemented!()
}
impl Foo {
// ... same as before
fn create_bar(&mut self) -> Bar {
if can_guarantee_option_bar_will_be_some() {
return self.create_option_bar().unwrap();
}
self.borrow_mut();
unimplemented!()
}
}
it works fine! now... what the heck is going on here? Aren't these both doing the same thing?
I want to know
- why is this not possible in the first scenario
- but is possible in the second
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/main.rs:44:9
|
37 | fn create_bar(&mut self) -> Bar {
| - let's call the lifetime of this reference `'1`
...
41 | if let Some(bar) = self.create_option_bar() {
| ------------------------ immutable borrow occurs here
42 | return bar;
| --- returning this value requires that `*self` is borrowed for `'1`
43 | }
44 | self.borrow_mut();
| ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
here is the full error ^