Skip to content

Insufficiently clear explanation of E0310 #54753

@gnzlbg

Description

@gnzlbg

The following program (Playground):

pub struct Foo<T>(T, &'static str);

pub trait Bar {
    fn baz(self) -> Box<dyn Baz>;
}

pub struct Bazzzz<T>(T, &'static str);

pub trait Baz {}
impl<T> Baz for Bazzzz<T> {}

impl<T> Bar for Foo<T> {
    fn baz(self) -> Box<dyn Baz> {
        Box::new(Bazzzz(self.0, self.1))
    }
}

fn main() {}

errors with

error[E0310]: the parameter type `T` may not live long enough
  --> src/main.rs:14:9
   |
12 | impl<T> Bar for Foo<T> {
   |      - help: consider adding an explicit lifetime bound `T: 'static`...
13 |     fn baz(self) -> Box<dyn Baz> {
14 |         Box::new(Bazzzz(self.0, self.1))
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: ...so that the type `Bazzzz<T>` will meet its required lifetime bounds
  --> src/main.rs:14:9
   |
14 |         Box::new(Bazzzz(self.0, self.1))
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0310`.
error: Could not compile `playground`.

From reading the explanation of E0310, which only mentions the situation in which T is used behind a static reference, e.g., foo: &'static T, I really had no idea what was going on. It seems that other people have had similar issues with this (e.g. https://stackoverflow.com/questions/40053550/the-compiler-suggests-i-add-a-static-lifetime-because-the-parameter-type-may-no ).

The explanation of E0310 should be improved to make it more clear why T: 'static is necessary, and what alternatives are there.

What confused me most is that T was not used in any reference type of the example above, but it was only used behind a reference in the example of the error message explanation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsC-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