Reputation: 308
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.
Upvotes: 0
Views: 98
Reputation: 16785
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
.
Upvotes: 1