Skip to content

Unhelpful error on implicit 'static lifetime for dyn Trait #85170

@jfrimmel

Description

@jfrimmel

Given the following code:

struct S(Vec<Box<dyn std::fmt::Debug>>);
impl S {
    fn update(&mut self) {
        let iter = self.0.iter_mut().map(|p| &mut **p);
        use_it(iter);
    }
}

fn use_it<'a, I: IntoIterator<Item = &'a mut dyn std::fmt::Debug>>(iter: I) {
    iter.into_iter().for_each(drop);
}

The current output is:

error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
 --> src/lib.rs:4:20
  |
3 |     fn update(&mut self) {
  |               --------- this data with an anonymous lifetime `'_`...
4 |         let iter = self.0.iter_mut().map(|p| &mut **p);
  |                    ^^^^^^ ...is captured here...
5 |         use_it(iter);
  |         ------ ...and is required to live as long as `'static` here

I initially thought, that the error refers to the reference.

At least I don't see the lifetime to the connection to the dyn Trait missing a lifetime, therefore the selected lifetime is 'static. The fix is to add another lifetime:

fn use_it<'a, 'b: 'a, I: IntoIterator<Item = &'a mut (dyn std::fmt::Debug + 'b)>>(iter: I) {
    iter.into_iter().for_each(drop);
}

Ideally an output would contain something mentioning the lifetime of the trait and not of the &mut-reference.

rustc 1.52.1 (9bc8c42bb 2021-05-09)
binary: rustc
commit-hash: 9bc8c42bb2f19e745a63f3445f1ac248fb015e53
commit-date: 2021-05-09
host: x86_64-unknown-linux-gnu
release: 1.52.1
LLVM version: 12.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-dyn-traitArea: trait objects, vtable layoutA-lifetimesArea: Lifetimes / regionsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions