I'm learning Rust coming from Python, and struggling with the concept of ownership and references.
I have a struct with properties bar1, bar2 and decider. Conditionally by the decider, I want to choose either bar1 or bar2 and call a method on it's &ref (immutable), using (now mutably!) another property of self:
#![allow(unused)]
struct Bar(u64);
impl Bar {
fn do_stuff(&self, x: &mut bool) {
// stuff
}
}
struct Foo {
bar1: Bar,
bar2: Bar,
decider: bool,
}
impl Foo {
fn get_bar<'a>(&'a self) -> &'a Bar {
if self.decider {
&self.bar1
} else {
&self.bar2
}
}
fn ok(&mut self) {
if self.decider {
self.bar1.do_stuff(&mut self.decider)
} else {
self.bar2.do_stuff(&mut self.decider)
}
}
fn error(&mut self) {
self.get_bar().do_stuff(&mut self.decider)
}
}
fn main() {}
While both methods do the same, the method ok() compiles, while error() is refused with the following error:
error[E0502]: cannot borrow `self.decider` as mutable because it is also borrowed as immutable
--> src/main.rs:32:33
|
32 | self.get_bar().do_stuff(&mut self.decider)
| -------------- -------- ^^^^^^^^^^^^^^^^^ mutable borrow occurs here
| | |
| | immutable borrow later used by call
| immutable borrow occurs here
How is what I want to do achievable?