T
T
tmshit2021-01-17 17:31:30
Rust
tmshit, 2021-01-17 17:31:30

How to fix "cannot infer an appropriate lifetime for lifetime parameter"?

There is a simplified version of the problematic code .
Crashes when compiling

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
  --> src/main.rs:58:18

Managed to fix it by changing the trait like this .
That is, an anonymous lifetime was added to the trait declaration
trait Encryptor {
    fn get_file(&self) -> Box<dyn File + '_>;
}
, and an explicit lifetime was added to the implementation:
impl<'a> Encryptor for Crypt<'a> {
    fn get_file(&self) -> Box<dyn File + 'a> {
        Box::new(F::new(self.wk, 11))
    }
}

Question: how, without changing the trait, to solve the problem of determining the appropriate lifetime in the implementation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2021-01-18
@tmshit

I don’t have much experience with growth itself, but as far as I understand, the situation is as follows:
1. The method fn get_file(&self)returns Box
2. Since the returned type Boxdoes not have an explicit lifetime constraint, according to RFC 599 , it is assigned a lifetime of 'static
3. But at the same time, the implementation of the trait Filestructure Fis limited to lifetime 'a, hence the conflict.
Possible solution: An
object that should be shared between other objects (in my example, this is WrappedKey) is wrapped first in Boxto move it from the stack to the heap, and then in Rcso that the object does not die while there is at least one reference to it.
When you need to create a copy of an object reference (to fumble around for that object), just call clone()on Rc.
If the object needs to be shared between different threads, then Rcuse Arc(Atomic RC) instead.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question