简体   繁体   中英

Passing lifetime to a struct

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.

您可能应该使用fn actions(&'a self)因为您在dyn Action + 'a使用的生命周期'aRpnCalculator的生命周期有关。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM