"borrowed value does not live long enough" in the same scope

Hi, folks! I'm stuck in a lifetime problem.

I can't understand, all variables are declared in the same function and I suppose that have the same lifetime

Here is the code:

fn main() {
    let candles = Vec::new();
    let candles_ref = candles.as_slice();
    let indicator_provider = IndicatorProvider::new(candles_ref);
    let macd_trend = MacdTrend::new(indicator_provider);

    let mut trader = Trader::new(Box::new(macd_trend));
    trader.check(candles_ref);
}

The error is this:

error[E0597]: `trader` does not live long enough
  --> src/main.rs:54:5
   |
54 |     trader.check(candles_ref);
   |     ^^^^^^ borrowed value does not live long enough
55 | }
   | -
   | |
   | `trader` dropped here while still borrowed
   | borrow might be used here, when `trader` is dropped and runs the destructor for type `Trader<'_>`

error: aborting due to previous error

The playground is here: Rust Playground

I tried a lot of combinations, removing + 'a of Trait Box, using two lifetimes like 'a: 'b and other things.

How I can resolve this error in this code?

I appreciate any help! Thank you.

You have several functions that take &'a mut self (i.e., borrow self for the same lifetime as the reference that it contains) when they should just take &mut self (i.e., borrow self for any amount of time).

Changing these to &mut self makes the program compile: Playground

I did not know this behavior of &'a mut self. Well, this code was a Minimal Reproducible Example, I put these &'a mut self for another reason. But now you explained why the problem occurs and help me a lot! Thank you very much!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.