Here is a minimal reproducible sample:
use std::fmt::{self, Debug, Formatter};
pub trait Apple {}
impl Debug for dyn Apple {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str("Apple")
}
}
struct Basket<'a> {
apples: Vec<Box<dyn Apple + 'a>>,
}
impl<'a> Basket<'a> {
fn f(&self) {
let x = format!("{:?}", self.apples);
}
}
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:17:17
|
17 | let x = format!("{:?}", self.apples);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined on the impl at 15:6...
--> src/lib.rs:15:6
|
15 | impl<'a> Basket<'a> {
| ^^
note: ...so that the types are compatible
--> src/lib.rs:17:17
|
17 | let x = format!("{:?}", self.apples);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
= note: expected `(&std::vec::Vec<std::boxed::Box<dyn Apple>>,)`
found `(&std::vec::Vec<std::boxed::Box<(dyn Apple + 'a)>>,)`
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the types are compatible
--> src/lib.rs:17:33
|
17 | let x = format!("{:?}", self.apples);
| ^^^^^^^^^^^
= note: expected `std::fmt::Debug`
found `std::fmt::Debug`
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
format!
should only borrow self.apples
for a very short period of time (only borrow during its formatting process). However, it even requires self.apples
to have the 'static
lifetime.
EDIT: Now I see why is that, after kind help from comments and other answers. According to @Shepmaster's suggestion, I move this part of content into an answer.