0

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() {}

Rust playground

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?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
M. Volf
  • 1,024
  • 12
  • 27
  • 1
    You need to [break apart the struct further](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d76ecd0b3d4158f4d90ad94488e88cff). – Shepmaster Dec 21 '21 at 16:36

0 Answers0