Apologies for the convoluted title!
I'm new to rust, and I'm trying to solve a very specific problem. None of the solutions I've tried so far seem to work nicely within the language bounds.
I have a struct that contains data (called Model), and it also contains a dynamic Box for a "strategy" struct. There are several different strategy structs, and they are identified by a common Trait (Strategy) that each contain a separate way of modifying the model through their "execute strategy" method. By doing this, the I can dynamically change which strategy is used by changing the model's strategy instance like a state-machine.
Each strategy is immutable, but they mutate the model's data. They do sometimes contain their own immutable data, so enums seemed like an awkward fit.
trait Strategy {
fn execute_strategy(&self, model: &mut Model);
}
struct Strategy1;
impl Strategy for Strategy1 {
fn execute_strategy(&self, model: &mut Model) {
...
}
}
struct Strategy2;
impl Strategy for Strategy2 {
fn execute_strategy(&self, model: &mut Model) {
...
}
}
struct Model {
strategy: Box<dyn Strategy>,
}
Now the place I'm running into issues is executing the strategy.
impl Model {
fn run(&mut self) {
(*self.strategy).execute_strategy(self); // WONT COMPILE
}
}
I get why the above won't compile -- It sees that self is borrowed immutably and mutably. Is there an idiomatic solution for this? Each strategy works in a vacuum and only modifies the model. The strategies themselves are immutable, so it seems like the above would be safe to do.
Happy New Year, and thanks in advance for the help!