Answer the question
In order to leave comments, you need to log in
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
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))
}
}
Answer the question
In order to leave comments, you need to log in
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 Box
does 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 File
structure F
is 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 Box
to move it from the stack to the heap, and then in Rc
so 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 Rc
use Arc
(Atomic RC) instead.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question