Skip to content

Static lifetime requirement in boxed trait object (Box<dyn Trait>) is not clearly explained #116765

Closed
@Tiwalun

Description

@Tiwalun

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

Metadata

Metadata

Assignees

Labels

A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutA-lifetimesArea: Lifetimes / regionsD-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions