Skip to content

rustc could explain that dyn Trait sometimes implies 'static #83246

Open
@comex

Description

@comex

In the following code: (playground link)

trait Foo {}
impl<'a> Foo for &'a u32 {}
impl dyn Foo {
    fn hello(&self) {}

}
fn convert<'a>(x: &'a &'a u32) {
    let y: &dyn Foo = x;
    y.hello();
}

The current output is:

error[E0759]: `x` has lifetime `'a` but it needs to satisfy a `'static` lifetime requirement
 --> src/lib.rs:8:23
  |
7 | fn convert<'a>(x: &'a &'a u32) {
  |                   ----------- this data with lifetime `'a`...
8 |     let y: &dyn Foo = x;
  |                       ^ ...is captured here...
9 |     y.hello();
  |       ----- ...and is required to live as long as `'static` here

The error is correct, yet I didn't write 'static anywhere in the program. What gives? This made me scratch my head for a few minutes. As it turns out, in impl dyn Foo, dyn Foo is treated as short for dyn Foo + 'static. The issue can be fixed by changing impl dyn Foo to impl<'a> dyn Foo + 'a.

I wouldn't say the current error is bad, exactly, but it would be nice if rustc could somehow warn the user about what's going on – either by warning on the impl itself, or by somehow attaching an explanation to the type error (though that might not be worth the complexity).

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsA-trait-systemArea: Trait systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.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