Closed
Description
Code
struct Factory<'a> {
value: &'a usize,
}
impl<'a> Factory<'a> {
fn generate(&self) -> Box<dyn std::fmt::Debug + 'a> {
Box::new(Value { value: self.value })
}
}
struct Owner {
value: Box<dyn std::fmt::Debug>
}
#[derive(Debug)]
struct Value<'a> {
value: &'a usize,
}
fn build_owner<'a,'b>(factory: &'b Factory<'a>) -> Owner {
let value = factory.generate();
Owner { value }
}
fn main() {
let value = 10;
let factory = Factory { value: &value };
let _owner = build_owner(&factory);
}
Current output
Compiling playground v0.0.1 (/playground)
error: lifetime may not live long enough
--> src/main.rs:29:13
|
26 | fn build_owner<'a,'b>(factory: &'b Factory<'a>) -> Owner {
| -- lifetime `'a` defined here
...
29 | Owner { value }
| ^^^^^ cast requires that `'a` must outlive `'static`
Desired output
error: lifetime may not live long enough
--> src/main.rs:29:13
|
26 | fn build_owner<'a,'b>(factory: &'b Factory<'a>) -> Owner {
| -- lifetime `'a` defined here
...
29 | Owner { value }
| ^^^^^ cast requires that `'a` must outlive `'static`
note: value has type Box<dyn Test>, which means that a default lifetime requirement of 'static is added.
note: Adding an explicit lifetime could help: Box<dyn Test +'a>
Rationale and extra context
I think it's not obvious that a boxed trait object means that there is a default lifetime requirement of 'static
, and I've spent too much time looking for where the 'static
requirement comes from. Would be great to get a hint from the compiler.
Other cases
No response
Anything else?
No response