0

I have code like this:

pub trait Action {
    fn execute(&self);
}

struct AddAction<'a> {
    rpn_calculator: &'a RpnCalculator
}

struct DeductAction<'a> {
    rpn_calculator: &'a RpnCalculator
}

impl Action for DeductAction<'_> {
    fn execute(&self) {
        // ...
    }
}

impl Action for AddAction<'_> {
    fn execute(&self) {
        // ...
    }
}

impl<'a> RpnCalculator {
    fn actions(&self) -> Vec<Box<dyn Action + 'a>> {
        let mut actions: Vec<Box<dyn Action + 'a>> = vec![
            Box::new(AddAction { rpn_calculator: &self })
            Box::new(AddAction { rpn_calculator: &self })
            // ...
        ];
        // ...
        actions
    }
}

The intention of my code is that RpnCalculator.actions() should create some instances of some structs that implement trait Action and return a vector containing those instances. Those structs have a property rpn_calculator which is a reference to a RpnCalculator. The RpnCalculator.actions() should put self (the RpnCalculator that creates it) into this reference.

Now the error I get is "cannot infer the appropiate lifetime". I get this error in the line where I create an instance that I add to the vector:

Box::new(AddAction { rpn_calculator: &self })

For that reason I have 'a in the vector declaration, but it still doesn't work.

Damian
  • 178
  • 11
  • 1
    Does this answer your question? [How to infer an appropriate lifetime for an implementation using lifetimes for structs and impl?](https://stackoverflow.com/questions/58422765/how-to-infer-an-appropriate-lifetime-for-an-implementation-using-lifetimes-for-s) – harmic Aug 30 '20 at 22:27

1 Answers1

1

You should probably use fn actions(&'a self) because the lifetime 'a you use in dyn Action + 'a is related to the lifetime of the RpnCalculator.

prog-fh
  • 13,492
  • 1
  • 15
  • 30