I'm trying to implement the chain of responsibility
from refactoring guru
https://refactoring.guru/design-patterns/chain-of-responsibility/rust/example
But instead I need to pass the object by reference as they need to be called later on
let cashier = Cashier::default();
let medical = Medical::new(&cashier); // instead of Medical::new(cashier)
But I'm having a hard time dealing with lifetimes, and references. To give a bit of detail, I get stuck here
pub(self) fn into_next(
department: impl Department + Sized + 'static,
) -> Option<Box<dyn Department>> {
Some(Box::new(department))
}
because trying to modify the parameter type to accept a reference leads later on to cannot borrow data in a & reference as mutable.
when trying to execute the next method
fn execute(&mut self, patient: &mut Patient) {
self.handle(patient);
if let Some(next) = &mut self.next() {
next.execute(patient);
}
}
what I've tried:
- removing all the
Box
as i want to work with references and from what I understandBox
take in the trait itself. - adding
'static
pretty much everywhere vscode wanted me to put some life times - added more scoped lifetimes (
'a
) where vscode told me after the'static
did not work - ... and other stupid things that obviously would not work because i'm loosing it...
If you need the code to run it, I'd recommend you clone the repo https://github.com/RefactoringGuru/design-patterns-rust/tree/main/behavioral/chain-of-responsibility